问题
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