HTML as sandboxed iframe&s; src`(IE11 / Edge)

时间:2018-01-06 00:54:36

标签: html5 iframe internet-explorer-11 sandbox microsoft-edge

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

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

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

1 个答案:

答案 0 :(得分:2)

假设需要或接受使用<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之后加载所有依赖项。