[英]How does angularjs prevent inline script tags from executing?
I was interested to know how AngularJS prevents inline <script>
tags from executing when they are included via the ng-include directive. 我很想知道AngularJS如何阻止内联<script>
标签在通过ng-include指令包含时执行。
After a template is included and the DOM is inspected, the script tags certainly exist, but they have not been executed. 在包含模板并检查DOM之后,脚本标记肯定存在,但它们尚未执行。 How are they being disarmed? 他们是如何被解除武装的?
I have begun reviewing the source code but any attempt I have made to include a script tag into the DOM myself (appendChild,
innerHTML
, innerText, document.write, etc.) always results in it being executed. 我已经开始查看源代码,但是我自己尝试将脚本标记包含到DOM中的任何尝试(appendChild,
innerHTML
,innerText,document.write等)总是导致它被执行。
Thank You. 谢谢。
That is an artifact of the way jqLite is implemented. 这是jqLite实现方式的工件。
To make script tags work, simply ensure that the jQuery library is loaded before the angular.js
file. 要使脚本标记有效,只需确保在angular.js
文件之前加载jQuery库。
<head>
<script src="//unpkg.com/jquery"></script>
<script src="//unpkg.com/angular/angular.js"></script>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
The DEMO on PLNKR . PLNKR上的DEMO 。
if you explain more that innerHTML is enough to prevent the script tags from executing I will select your answer as correct 如果您更多地解释innerHTML足以阻止脚本标记执行,我将选择您的答案为正确
HTML5 specifies that a <script>
tag inserted with innerHTML
should not execute. HTML5指定不应执行使用innerHTML
插入的<script>
标记。
However, there are ways to execute JavaScript without using <script>
elements, so there is still a security risk whenever you use innerHTML
to set strings over which you have no control. 但是,有一些方法可以在不使用<script>
元素的情况下执行JavaScript,因此每当使用innerHTML
设置无法控制的字符串时,仍然存在安全风险。 For example: 例如:
const name = "<img src='x' onerror='alert(1)'>";
el.innerHTML = name; // shows the alert
For that reason, it is recommended you not use innerHTML
when inserting plain text; 因此,建议您在插入纯文本时不要使用innerHTML
; instead, use Node.textContent
. 相反,使用Node.textContent
。 This doesn't parse the passed content as HTML, but instead inserts it as raw text. 这不会将传递的内容解析为HTML,而是将其作为原始文本插入。
For more information, see MDN Web API Reference - Element.innerHTML . 有关更多信息,请参阅MDN Web API参考 - Element.innerHTML 。
It looks like ng-include calls $element.html(ctrl.template);
它看起来像ng-include调用$element.html(ctrl.template);
See source on GitHub 请参阅GitHub上的源代码
The html function of jqLite then uses element.innerHTML = value;
然后jqLite的html函数使用element.innerHTML = value;
to insert the content. 插入内容。 See source on GitHub 请参阅GitHub上的源代码
And after testing - it looks like that is enough to not execute <script>
tags. 经过测试 - 看起来就足以不执行<script>
标签了。
I've created a jsFiddle here. 我在这里创建了一个jsFiddle。 - #3 is the equivalent of what AngularJS is doing and it does not execute the script tags. - #3相当于AngularJS正在做的事情,它不执行脚本标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.