Skip to content

Instantly share code, notes, and snippets.

@kevinbuhmann
Last active September 20, 2017 19:45
Show Gist options
  • Save kevinbuhmann/20ea29ba8458d75befa195005a72310f to your computer and use it in GitHub Desktop.
Save kevinbuhmann/20ea29ba8458d75befa195005a72310f to your computer and use it in GitHub Desktop.
"[innerHTML] causes the server to duplicate content" workaround (angular/angular#19278)
import { parse, serialize, AST } from 'parse5';
export function transformHtml(html: string, visitors: NodeVisitor[]) {
const document = parse(html) as AST.Default.Document;
visitNode(document, visitors);
return serialize(document);
}
export function removeInnerHtmlAttributes(node: any) {
if (node.attrs) {
const element = node as AST.Default.Element;
const innerHtmlAttributeIndex = element.attrs.findIndex(attr => attr.name === 'innerhtml');
if (innerHtmlAttributeIndex > -1) {
element.attrs.splice(innerHtmlAttributeIndex, 1);
}
}
}
function visitNode(node: any, visitors: NodeVisitor[]) {
for (const visitor of visitors) {
visitor(node);
}
if (node.childNodes) {
for (const childNode of node.childNodes) {
visitNode(childNode, visitors);
}
}
}
import { renderModuleFactory } from '@angular/platform-server';
import { Response } from 'express';
import * as fs from 'fs';
import { removeInnerHtmlAttributes, transformHtml } from './parse5-helpers';
import { AppServerModuleFactory } from './wherever';
const document = fs.readFileSync('index.html').toString();
export function render(url: string, response: Response) {
renderModuleFactory(AppServerModuleFactory, { url, document })
.then(html => transformHtml(html, [removeInnerHtmlAttributes]))
.then(html => { response.status(200).type('html').send(html); });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment