所以我用window.open('https://example.com/foo')
打开了一个窗口。我在同一个域中,需要监听加载事件。
加载事件会触发第一个window.open
,但是当我使用window.replace('https://example.com/bar')
更改网址时,我无法获得另一个事件
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'));
});
答案 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(一勾)->加载