简体   繁体   中英

Manipulating the DOM with JS in angular 2+ to run scripts

I need to insert a script into an angular project which looks like this.

<script type="text/javascript" src="https://s3.tradingview.com/external-
embedding/embed-widget-events.js">
{
"width": "510",
"height": "600",
"importanceFilter": "-1,0,1"
}
</script>

Obviously, can't just stick it into template because NG will sanitize the script tag and nothing will happen. So I have a method that manipulates the DOM which looks like this.

insertScript() {

    var element = document.getElementById("myCal");
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = "https://s3.tradingview.com/external-embedding/embed-widget-events.js";
    script.innerHTML = '{"width": "510","height": "600","importanceFilter": "-1,0,1"}';
    element.appendChild(script);
    console.log(element);
}

Now, I run the method on ngAfterViewInit() after angular is done with sanitization so we don't get into that process. The script gets inserted, the console output shows it at the div and you can inspect to see it there however nothing happens!!!

I checked the script in an ordinary html context outside the project it works perfectly.

Don't know where to move on from here really, any suggestions would be really appreciated. Thanks.

After numerous attempts to insert the widget the answer was quite surprising. When we understood the chronology of the call it looked like this.

1) External js sourced 2) Then because of our dome manipulations the script was actually called correctly however nothing was inserted because the js sourced made calls to another source which was sanitized.

We solved the problem by going to the trading view page, inspecting the iframe that was inserted there and that was where we saw the actual true source from where the widget was being loaded. After we bypassed the security for that source the widget loaded.

this.calendarSrc = 
        this.sanitizer
        .bypassSecurityTrustResourceUrl('the real source');

Very tricky issue it was and we tried every possible dome manipulation there can be to solve it but the answer was on the surface.

In the html template in angular we simply stick an iframe and for the iframe source the real source we got from the iframe from trading view website. In the iframe we substitute a variable for the source and we by pass security for the variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM