I have load the HTML
page by http.get()
method, and i add content this page to div tag.
getRequestToAssignPage (param: string) : any {
return this.$http.get(param)
.map((res: Response) => {
this.status = res;
return res.text();
})
.toPromise()
.then(response => {
let restr: string = response;
restr = restr.replace(/(<head[^>]*)(?:[^])*?\/head>/ig, '')
.replace(/(<(\/?)body([^>]*?)>)/g, '')
.replace(/(<style[^>]*)(?:[^])*?\/style>/g, '')
.replace(/(<(\/?)html([^>]*?)>)/g, '')
.replace(/(<app-root[^>]*)(?:[^])*?\/app-root>/ig, '')
.replace(/(<\?[\s\S]*?\?>)|(<!DOCTYPE\s+\w+\s+\[[\s\S]*?\]>)|(<!\w[\s\S]*?>)/g, '')
.replace(/(href\s*=\s*(?:"))/ig, 'href="/#')
.replace(/(href\s*=\s*(?:'))/ig, "href='/#");
this.response = restr;
})
.catch(error => this.status = error );
}
How you do you see, this method, put response in variable, and parse string by regular expressions Ok, and next I add it to div, like this
<div [innerHTML]="response | safe"></div>
Good, my page is display. But, scripts doesn't work. They are exist in the div tag, but doesn't execute.
I had tried do that with eval()
but this finished by poorly
let scripts: string[] = restr.match(/\<scr[\s\S]*?ipt>/g);
this.srcfield.nativeElement.innerHTML = '';
scripts.forEach((value, index) => {
eval.call(null, (this.srcfield.nativeElement.innerHTML = value));
});
SyntaxError: Unexpected token <
Why innerHTML
doesn't execute loaded script tags? How i can fix that?
In your template, you can set up something like:
In the corresponding component, you can load your HTML into your template, build up an array of script tags, and
eval
each one:I hate that I have to resort to using
setTimeout
andeval
for something so seemingly simple, but it works....but not for
<script src="...
. I ended up importing jQuery and using$(parent).load(url);
. If someone has a pure Angular solution, please post it.Based on the Adam's solution you can implement a custom directive along with the pipe and re-insert scripts into the DOM. This would account for both cases: inline scripts and "src" scripts. Keep in mind that allowing scripts like so is very dangerous.
Pipe:
Directive:
Usage: