Why doesn't a browser run a <script> in an HTML fragment retrieved via fetch API? [duplicate]

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 06:23:33

问题


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.

Below is an example. I would expect the alert to fire, but it doesn't, even though the script tag appears on the page.

My questions are (1) why does the <script> not get evaluated, and (2) is there a way to make it evaluate?

index.html

<!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)
})

回答1:


Because that's what the HTML spec dictates:

script elements inserted using innerHTML do not execute when they are inserted.

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.


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);


来源:https://stackoverflow.com/questions/49867200/why-doesnt-a-browser-run-a-script-in-an-html-fragment-retrieved-via-fetch-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!