如何在location.replace(url更改)之后捕获窗口的load事件

loading...


1

所以我用 window.open('https://example.com/foo') 打开了一个窗口 . 我在同一个域上,需要监听加载事件 .

第一个 window.open 的load事件触发但是当我用 window.replace('https://example.com/bar') 更改url时我无法获得另一个事件

CodeSandbox

  • 打开浏览器控制台

  • 单击打开按钮(观察控制台中的日志)

  • 单击切换按钮(观察没有记录任何内容)

完整的例子

let open = null;
document.getElementById('open-button').addEventListener('click', () => {
  open = window.open('https://523k29z484.codesandbox.io/pages/foo.html');
  open.addEventListener('load', () => console.log('this fires'));
});

document.getElementById('switch-button').addEventListener('click', () => {
  open.addEventListener('load', () => console.log('before change does not fire'));
  open.location.replace('https://523k29z484.codesandbox.io/pages/bar.html');
  open.addEventListener('load', () => console.log('after change does not fire'));
});

loading...

1回答

  • 0

    我通过仔细链接以下代码解决了这个问题 .

    open.location.replace('https://211vv50z30.codesandbox.io/pages/bar.html');
    
    // old page unloaded
    open.addEventListener('unload', () => {
      // we can only add the load event after one tick
      setTimeout(() => {
        open.addEventListener('load', () => console.log('gotcha'));
      }, 0);
    });
    

    location.replace - > unload - > setTimeout(一个tick) - > load

    CodeSandbox

评论

暂时没有评论!