如何在location.replace(URL更改)之后捕获窗口的加载事件

时间:2018-12-10 10:30:20

标签: javascript dom browser

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

加载事件会触发第一个window.open,但是当我使用window.replace('https://example.com/bar')更改网址时,我无法获得另一个事件

CodeSandbox

Edit static

  1. 打开浏览器控制台
  2. 单击打开按钮(在控制台中查看日志)
  3. 单击“切换”按钮(注意什么都不会记录)

完整示例

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'));
});

1 个答案:

答案 0 :(得分: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->卸载-> setTimeout(一勾)->加载

CodeSandbox

Edit fixed window load problem