所以我用 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'));
});
1 回答
我通过仔细链接以下代码解决了这个问题 .
location.replace - > unload - > setTimeout(一个tick) - > load
CodeSandbox