`隐式射击''而不是“可见”对于新窗口初始加载
我正在启动一个新选项卡,并尝试添加窗口的visibilityChange
处理程序,以添加卸载行为,因为所有文档都建议通过onunload
和page> pagehide。
。我的计划是附加侦听器,并且当文档的vistibilitystate
更改为隐藏>
,无论是通过明确关闭还是只是浏览或其他东西,都可以关闭标签父窗口触发一些功能。
该代码大致如下:
var testTab = window.open(myPath, 'testTab');
testTab.addEventListener('visibilitychange', function () {
if(testTab.document.visibilityState === 'hidden'){
onHidden();
}
else {
onVisible();
}
});
testTab.focus();
但是,当打开“新选项卡”时,侦听器会在加载窗口的任何内容之前使用hidden
distibilityState 。此后,即使窗口完成加载和渲染时,该事件也不会再次发射。如果我然后隐藏选项卡(例如,在同一窗口中打开原始选项卡),则事件以hidden
按预期发射。然后返回打开的选项卡将按预期触发事件,如可见
。
该页面如何在初始加载上似乎没有正确的vistibilitystate
?如果它开始隐藏,然后一旦渲染或类似的东西就过渡到可见的,那么我就可以理解它,但是只有在初始渲染上隐藏起来似乎很腥。我必须假设我做错了什么。
编辑:出于好奇,我尝试使用pagehide
,并且遇到了相同的问题。在加载任何内容之前,新窗口首次打开时,它会立即触发。我不确定我出错了哪里。
edit2:卸载/toterunload
在页面加载上确实可以按预期工作(即他们根本不发射),并在卸载时正确发射(duh。),但不要共享挂钩的能力进入其他形式的可见性损失,并且通常建议在我能找到的所有内容中,尤其是因为它的移动支持。
I am launching a new tab and trying to add a visibilitychange
handler for the window in order to add unload behavior, since all the docs recommend that over onunload
and pagehide
. My plan was to attach the listener, and when the document's visibilityState
changed to hidden
, whether by explicitly closing it or just navigating away or something, to close the tab and have the parent window trigger some functionality.
The code is roughly as follows:
var testTab = window.open(myPath, 'testTab');
testTab.addEventListener('visibilitychange', function () {
if(testTab.document.visibilityState === 'hidden'){
onHidden();
}
else {
onVisible();
}
});
testTab.focus();
However, when the new tab is opened, the listener fires with the hidden
visibilityState
before any content of the window is loaded. The event does not fire again after that, even by the time the window has finished loading and rendering. If I then hide the tab (by any means, eg. open the original tab in the same window), the event fires with hidden
as expected. Then going back to the opened tab will trigger the event as visible
, as expected.
How come the page doesn't seem to have the correct visibilityState
on the initial load? I could make sense of it if it started hidden, and then transitioned to visible once it finished rendering or something like that, but it being hidden only on initial render seems very fishy; I have to assume I'm doing something wrong.
Edit: Out of curiosity, I tried using pagehide
and it suffers from the same problem. It is being triggered immediately when the new window first opens, before any content has been loaded. I'm not sure where I'm going wrong.
Edit2: unload/beforeunload
do work as expected on page load (ie. they don't fire at all), and do properly fire on unload (duh.) but don't share the ability to hook into other forms of visibility loss, and is generally advised against in everything I could find, especially because of its mobile support.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试此代码。
try this code.