Why doesn#39;t a browser run a lt;scriptgt; in an HTML fragment retrieved via fetch API?(为什么浏览器不运行lt;脚本gt;在通过 fetch API 检索的 HTML 片段中?)
问题描述
我正在尝试使用 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="bWFpbi5qcw=="></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 片段中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么浏览器不运行<脚本>在通过 fetch API 检索的 HTML 片段中?


- Fetch API 如何获取响应体? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07