0

我在一个页面上加载了多个 iframe,我的目标是在父页面完成加载后立即加载这些 iframe,但是我不希望在加载 iframe 时重新加载父页面。我试图做的是在父页面窗口完成加载时添加一个事件侦听器,然后继续并将 iframe 附加到页面。但是,这会导致父页面重新加载。代码参考如下。也只是添加 iframe 来自与父页面不同的域。

const iFrameResize = (obj) => { console.log(obj) }
const style = "Bla";
window.onload = function() {
  console.log('hey..........')
  var iframe = document.createElement('iframe')
  iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms"
  iframe.src = "https://iframe.domain.com"
  iframe.width = "100%"
  iframe.frameBorder = "0"
  iframe.id = "iframe-1"
  iframe.onload = function onloadHandler(e) {
    var iframe = e.target
    var iframeId = '#' + iframe.id
    iFrameResize({
      log: true
    }, iframeId)
    iframe.contentWindow.postMessage(style, "*");
  }
  document.body.appendChild(iframe)
}

4

1 回答 1

0

如果确实 window.onload 冒泡,也许试试这个

const iFrameResize = (obj,sel) => {
  console.log(obj,sel)
  document.querySelector(sel).style.display="block";
}
const style = "Bla";

function onloadHandler(e) {
  const iFrame = e.target;
  console.log(iFrame.src)
  const iframeSelector = '#' + iFrame.id
  iFrameResize({
    log: true
  }, iframeSelector)
  iFrame.contentWindow.postMessage(style, "*");
}

window.addEventListener("load", e => {
  console.log(e.target.location.href)
  const iframe = document.createElement('iframe')
  iframe.sandbox = "allow-same-origin allow-scripts allow-popups allow-forms"
  iframe.width = "100%"
  iframe.frameBorder = "0"
  iframe.style.display="none";
  iframe.id = "iframe-"+document.querySelectorAll("iframe").length;
  iframe.addEventListener("load", onloadHandler);
  iframe.src = "https://google.com/search?q="+iframe.id
  document.body.appendChild(iframe)
})

于 2020-04-30T12:33:35.240 回答