gpt4 book ai didi

HTML 作为沙盒 iframe 的 `src` (IE11/Edge)

转载 作者:可可西里 更新时间:2023-11-01 12:57:13 29 4
gpt4 key购买 nike

对于 HTML5,除了使用 <iframe sandbox></iframe> 之外,IE11/Edge 中是否有任何方法可以使用 HTML 填充沙盒 iframe ( src )网址?我正在寻找类似 srcdoc 的解决方案适用于所有其他现代浏览器。

使用 srcdata URI不是一个选项according to Microsoft因为它“不能用于 [to] 填充框架或 iframe 元素。”令人惊讶的是,这在 Edge 中对我有用,但仅适用于少于 4096 个字符的数据 URI。

我找到的所有其他选项,例如在 Alternatives to iframe srcdoc? Html code as IFRAME source rather than a URL 不适用于沙盒 iframe。

最佳答案

假设使用 <iframe sandbox="allow-scripts">是需要的或可以接受的,一个可能的解决方法是使用 window.postMessage() 使用以下设置:

index.html:

<!doctype html>
<html>
<body>
<iframe onload="connectIframe()" sandbox="allow-scripts" src="iframeConnect.html" name="srcdocloader"></iframe>
<script>

var SRCDOC_HTML = '<html><body><script src="https://code.jquery.com/jquery-3.2.1.js"><\/script><script>console.log("loaded srcdoc and dependencies", jQuery);<\/script><h1>done!</h1></body></html>';
var loaded;

function connectIframe (event) {
if (!loaded) {
loaded = true;
window.frames.srcdocloader.postMessage(SRCDOC_HTML, '*');
} else {
onloadSrcdoc();
}
}

function onloadSrcdoc () {
// ...
}

</script>
</body>
</html>

iframeConnect.html:

<!doctype html>
<script>
window.addEventListener("message", handler);
function handler(event) {
if (event.source === window.parent) {
window.removeEventListener("message", handler);
document.write(event.data);
document.close();
}
}
</script>

请注意 iframe 的 onload事件将被触发两次。第二次将在 srcdoc 之后html 及其所有依赖项都已加载。

关于HTML 作为沙盒 iframe 的 `src` (IE11/Edge),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48123273/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com