作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
对于 HTML5,除了使用 <iframe sandbox></iframe>
之外,IE11/Edge 中是否有任何方法可以使用 HTML 填充沙盒 iframe ( src
)网址?我正在寻找类似 srcdoc
的解决方案适用于所有其他现代浏览器。
使用 src
用data 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/
我是一名优秀的程序员,十分优秀!