[英]load multiple script tag in angular component
I'm trying to load a series of scripts from a component of an angular application, I want to do it in a specific component and not in the index.html but I can't find a way to do it, any help or advice?我正在尝试从 angular 应用程序的组件加载一系列脚本,我想在特定组件中执行此操作,而不是在 index.html 中执行此操作,但我找不到执行此操作的方法,任何帮助或建议?
this is my code home.component.html这是我的代码home.component.html
<div class="row">
<div id="webchat" style="position: relative;z-index: 999999;"></div>
<script>
window.GB_SETUP={websocket_url: "wss://api-mychat.com", type:"config",
channel: "6342", session_id: "34345", style:"343234"};
</script>
<script src="https://myscript.com/script.js"></script>
<script src="https://myscript.com/script2.js"></script>
</div>
If I copy and paste as is in the index.html of the project it works great, but I want to do it inside a component如果我按原样复制并粘贴到项目的 index.html 中,效果很好,但我想在组件内部进行
Angular ignores all script
tags in templates for security reasons (to prevent cross-site-scripting / XSS). Angular 出于安全原因忽略模板中的所有
script
标签(以防止跨站点脚本/XSS)。
To eliminate the risk of script injection attacks, Angular does not support the
script
element in templates.为了消除脚本注入攻击的风险,Angular 不支持模板中的
script
元素。 Angular ignores thescript
tag and outputs a warning to the browser console.Angular 忽略
script
标签并向浏览器控制台输出警告。
https://angular.io/guide/template-syntax#empower-your-html https://angular.io/guide/template-syntax#empower-your-html
As a workaround you could inject the script programmatically in your component's ts
file, like so...作为一种解决方法,您可以在组件的
ts
文件中以编程方式注入脚本,就像这样......
@Component({
...
})
export class HomeComponent implements OnInit {
...
constructor(
@Inject(DOCUMENT) private document: Document
) { }
ngOnInit(): void {
this.injectScript("https://myscript.com/script.js");
this.injectScript("https://myscript.com/script2.js");
}
public injectScript(src: string) {
if(this.document && src?.trim()) {
const script = this.document.createElement("script");
script.setAttribute("type","text/javascript");
script.setAttribute("src",src.trim());
this.document.head?.appendChild(script);
}
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.