从PC/Windows本地执行时,加载iframe、复制和删除iframe不起作用



下面的代码在服务器上执行时可以工作,但在我的电脑上失败了。我试过Chrome,Edge。

<!DOCTYPE html>
<meta charset="utf-8">
<title>HTML Includes</title>
<body>
<h1>The Simplest Ways to Handle HTML Includes</h1>
<h3>https://www.filamentgroup.com/lab/html-includes/</h3>
<p>Load iframe, copy to &lt;div&gt; before, and remove iframe.
<p>If the background is gray, then removing the iframe failed.
<p>Works from server, but not from a local file.</p>
<div></div>
<iframe name="content" style="background-color: lightgrey; width:100%" src="fff.html" onload="this.before((this.contentDocument.body||this.contentDocument).children[0]);this.remove(); ">
</iframe>
</body>

我得到以下错误:

fff.html:14 

Uncaught TypeError: Cannot read properties of null (reading 'body')
at HTMLIFrameElement.onload (fff.html:14:143)

有了Firefox,它就可以工作了。

此问题与CORS有关。由于html文档和其中的iframe都加载了file:///模式,因此它们的来源被视为不透明来源,如下所述:

现代浏览器通常会处理使用file:///模式为不透明原点。这意味着如果包括来自同一文件夹的其他文件(例如(,它们不是假定的并且可能触发CORS错误。

Chrome就是这样,Edge也使用Chrome闪烁引擎,但Firefox不是这样
因此,contentDocument返回null,如这里所述,因为在这种情况下,iframe及其父文档不是同源文档。因此,代码this.contentDocument.body触发了错误,没有到达this.remove(),这就是为什么什么都不起作用。

最新更新