问题描述
我正在尝试使用 fetch API 获取 HTML 片段,然后将其添加到 HTML 页面.虽然这适用于 HTML 内容,但我注意到如果我在片段中放置一个 <script>
标记,该标记不会被剥离,但它也不会被执行.
I was experimenting with getting a fragment of HTML using the fetch API, and then adding it to an HTML page. While this works fine for HTML content, I noticed that if I put a <script>
tag in the fragment, the tag isn't stripped out, but it also isn't executed.
下面是一个例子.我希望 alert
会触发,但它不会触发,即使脚本标记出现在页面上.
Below is an example. I would expect the alert
to fire, but it doesn't, even though the script tag appears on the page.
我的问题是 (1) 为什么 <script>
没有得到评估,以及 (2) 有没有办法让它评估?
My questions are (1) why does the <script>
not get evaluated, and (2) is there a way to make it evaluate?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Index</title>
</head>
<body>
<script src="main.js"></script>
</body>
</html>
fragment.html
<h1>Hello</h1>
<p>It works</p>
<script>
alert('hello') // doesn't work, but script still appears on page
</script>
main.js
fetch('fragment.html').then((res)=>{
return res.text()
}).then((data)=>{
var div = document.createElement('div')
div.innerHTML = data
document.body.appendChild(div)
})
推荐答案
因为这就是 HTML 规范规定:
使用innerHTML 插入的脚本元素在被插入时不会执行插入.
script elements inserted using innerHTML do not execute when they are inserted.
我在这里做出假设,但可能是为了引入一层安全性,这样您就不会意外引入 XSS 或 代码注入.
I'm making assumptions here, but it's probably to introduce a layer of security so that you don't accidentally introduce XSS or code injection.
如果你想让脚本运行,获取它们的内容,创建一个特定的 <script>
元素,将脚本的主体设置为内容,然后将其插入到 DOM 中:
If you want to get the scripts to run, take their content, create a specific <script>
element, set the script's body to the content, and then insert that into the DOM:
const script = document.createElement("script"),
text = document.createTextNode("console.log('foo')");
script.appendChild(text);
document.body.appendChild(script);
这篇关于为什么浏览器不运行<脚本>在通过 fetch API 检索的 HTML 片段中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!