gpt4 book ai didi

javascript - 使用 ALT+TAB 切换程序/窗口或单击任务栏时不会触发 visibilitychange 事件

转载 作者:技术小花猫 更新时间:2023-10-29 12:08:13 32 4
gpt4 key购买 nike

问题出在事件“visibilitychange”的行为上。

触发: - 当我切换到浏览器窗口内的不同选项卡时。

  • 当我点击浏览器窗口的最小化/恢复按钮时。

(没关系)

未触发: - 当我使用 ALT+TAB 切换到不同的窗口/程序时。

  • 当我切换到不同的窗口/程序时单击任务栏。

(这应该触发,因为就像最小化时一样,窗口的可见性可能会改变)


W3 页面可见性 API 文档:http://www.w3.org/TR/page-visibility/

规范表中没有关于 ALT+TAB/程序切换的“页面可见性”定义。我猜它在操作系统和浏览器之间有一些关系。


已测试

  • 浏览器:Chrome 40.0.2214.115 m/Firefox 36.0.1/Internet Explorer 11.0.9600.17107
  • 操作系统:Windows 8.1

是否有解决此问题的解决方法?实现相当简单,我使用 jQuery 监听“visibilitychange”事件,然后在其回调中检查“document.visibilityState”的值,但问题是事件没有按预期触发。

$(document).on('visibilitychange', function() {

if(document.visibilityState == 'hidden') {
// page is hidden
} else {
// page is visible
}
});

这也可以在没有 jQuery 的情况下完成,但是 ALT+TAB 和任务栏切换隐藏/显示预期行为仍然缺失:

if(document.addEventListener){
document.addEventListener("visibilitychange", function() {
// check for page visibility
});
}

我也试过 ifvisible.js 模块 ( https://github.com/serkanyersen/ifvisible.js ),但行为是一样的。

ifvisible.on('blur', function() {
// page is hidden
});

ifvisible.on('focus', function() {
// page is visible
});

我还没有在其他浏览器中测试过,因为如果我不能让它在 Windows 上的 Chrome 中工作,我真的不关心其他浏览器。

有什么帮助或建议吗?


更新

我尝试为事件名称使用不同的 vendor 前缀(visibilitychange、webkitvisibilitychange、mozvisibilitychange、msvisibilitychange),但是当我切换到任务栏中的不同程序或 ALT+ 时,事件仍然没有触发TAB,或者即使我使用覆盖整个屏幕的 Windows 键打开 Windows 中的开始菜单。

我可以在 Chrome、Firefox 和 Internet Explorer 中重现完全相同的问题。

更新 #2

Here's我为这个问题写的一篇综述文章和一个纯 Javascript 解决方法来解决遇到的问题。

更新 #3

编辑以包含来源博客文章的副本。 (见接受的答案)

最佳答案

Here's我为这个问题写的一篇综述文章和一个纯 JavaScript 的变通方法来解决遇到的问题。

编辑以包含来源博客文章的副本:


In any kind of javascript application we develop there may be afeature or any change in the application which reacts according to thecurrent user visibility state, this could be to pause a playing videowhen the user ALT+TABs to a different window, tracking stats about howthe users interact with our application, how often does him switch toa different tab, how long does it take him to return and a lot ofperformance improvements that can benefit from this kind of API.

The Page Visibility API provides us with two top-level attributes:document.hidden (boolean) and document.visibilityState (which could beany of these strings: “hidden”, “visible”, “prerender”, “unloaded”).This would not be not good enough without an event we could listen tothough, that’s why the API also provides the useful visibilitychangeevent.

So, here’s a basic example on how we could take action on a visibilitychange:

function handleVisibilityChange() {
if(document.hidden) {
// the page is hidden
} else {
// the page is visible
}
}

document.addEventListener("visibilitychange", handleVisibilityChange, false);

We could also check for document.visibilityState value.

Dealing with vendor issues George Berkeley by John Smibert

Some of the implementations on some browsers still need that theattributes or even the event name is vendor-prefixed, this means wemay need to listen to the msvisibilitychange event or check for thedocument.webkitHidden or the document.mozHidden attributes. In orderto do so, we should check if any vendor-prefixed attribute is set, andonce we know which one is the one used in the current browser (only ifthere’s the need for a prefix), we can name the event and attributesproperly.

Here’s an example approach on how to handle these prefixes:

var browserPrefixes = ['moz', 'ms', 'o', 'webkit'];

// get the correct attribute name
function getHiddenPropertyName(prefix) {
return (prefix ? prefix + 'Hidden' : 'hidden');
}

// get the correct event name
function getVisibilityEvent(prefix) {
return (prefix ? prefix : '') + 'visibilitychange';
}

// get current browser vendor prefix
function getBrowserPrefix() {
for (var i = 0; i < browserPrefixes.length; i++) {
if(getHiddenPropertyName(browserPrefixes[i]) in document) {
// return vendor prefix
return browserPrefixes[i];
}
}

// no vendor prefix needed
return null;
}

// bind and handle events
var browserPrefix = getBrowserPrefix();

function handleVisibilityChange() {
if(document[getHiddenPropertyName(browserPrefix )]) {
// the page is hidden
console.log('hidden');
} else {
// the page is visible
console.log('visible');
}
}

document.addEventListener(getVisibilityEvent(browserPrefix), handleVisibilityChange, false);

Other issues There is a challenging issue around the “Page Visibility”definition: how to determine if the application is visible or not ifthe window focus is lost for another window, but not the actualvisibility on the screen? what about different kinds of visibilitylost, like ALT+TAB, WIN/MAC key (start menu / dash), taskbar/dockactions, WIN+L (lock screen), window minimize, window close, tabswitching. What about the behaviour on mobile devices?

There’s lots of ways in which we may lose or gain visibility and a lotof possible interactions between the browser and the OS, therefore Idon’t think there’s a proper and complete “visible page” definition inthe W3C spec. This is the definition we get for the document.hiddenattribute:

HIDDEN ATTRIBUTE On getting, the hidden attribute MUST return true ifthe Document contained by the top level browsing context (root windowin the browser’s viewport) [HTML5] is not visible at all. Theattribute MUST return false if the Document contained by the top levelbrowsing context is at least partially visible on at least one screen.

If the defaultView of the Document is null, on getting, the hiddenattribute MUST return true.

To accommodate accessibility tools that are typically full screen butstill show a view of the page, when applicable, this attribute MAYreturn false when the User Agent is not minimized but is fullyobscured by other applications.

I’ve found several inconsistencies on when the event is actuallyfired, for example (Chrome 41.0.2272.101 m, on Windows 8.1) the eventis not fired when I ALT+TAB to a different window/program nor when IALT+TAB again to return, but it IS fired if I CTRL+TAB and thenCTRL+SHIFT+TAB to switch between browser tabs. It’s also fired when Iclick on the minimize button, but it’s not fired if the window is notmaximized and I click my editor window which is behing the browserwindow. So the behaviour of this API and it’s differentimplementations are still obscure.

A workaround for this, is to compensate taking advantage of the betterimplemented focus and blur events, and making a custom approach to thewhole “Page Visibility” issue using an internal flag to preventmultiple executions, this is what I’ve come up with:

var browserPrefixes = ['moz', 'ms', 'o', 'webkit'],
isVisible = true; // internal flag, defaults to true

// get the correct attribute name
function getHiddenPropertyName(prefix) {
return (prefix ? prefix + 'Hidden' : 'hidden');
}

// get the correct event name
function getVisibilityEvent(prefix) {
return (prefix ? prefix : '') + 'visibilitychange';
}

// get current browser vendor prefix
function getBrowserPrefix() {
for (var i = 0; i < browserPrefixes.length; i++) {
if(getHiddenPropertyName(browserPrefixes[i]) in document) {
// return vendor prefix
return browserPrefixes[i];
}
}

// no vendor prefix needed
return null;
}

// bind and handle events
var browserPrefix = getBrowserPrefix(),
hiddenPropertyName = getHiddenPropertyName(browserPrefix),
visibilityEventName = getVisibilityEvent(browserPrefix);

function onVisible() {
// prevent double execution
if(isVisible) {
return;
}

// change flag value
isVisible = true;
console.log('visible}

function onHidden() {
// prevent double execution
if(!isVisible) {
return;
}

// change flag value
isVisible = false;
console.log('hidden}

function handleVisibilityChange(forcedFlag) {
// forcedFlag is a boolean when this event handler is triggered by a
// focus or blur eventotherwise it's an Event object
if(typeof forcedFlag === "boolean") {
if(forcedFlag) {
return onVisible();
}

return onHidden();
}

if(document[hiddenPropertyName]) {
return onHidden();
}

return onVisible();
}

document.addEventListener(visibilityEventName, handleVisibilityChange, false);

// extra event listeners for better behaviour
document.addEventListener('focus', function() {
handleVisibilityChange(true);
}, false);

document.addEventListener('blur', function() {
handleVisibilityChange(false);
}, false);

window.addEventListener('focus', function() {
handleVisibilityChange(true);
}, false);

window.addEventListener('blur', function() {
handleVisibilityChange(false);
}, false);

I welcome any feedback on this workaround. Some other great sourcesfor ideas on this subject:

Using the Page Visibility API Using PC Hardware more efficiently inHTML5: New Web Performance APIs, Part 2 Introduction to the PageVisibility API Conclusion The technologies of the web are continuouslyevolving, we’re still recovering from a dark past where tables wherethe markup king, where semantics didn’t mattered, and they weren’t anystandards around how a browser should render a page.

It’s important we push these new standards forward, but sometimes ourdevelopment requirements make us still need to adapt to these kind oftransitions, by handling vendor prefixes, testing in differentbrowsers and differents OSs or depend on third-party tools to properlyidentify this differences.

We can only hope for a future where the W3C specifications arestrictly revised, strictly implemented by the browser developer teams,and maybe one day we will have a common standard for all of us to workwith.

As for the Page Visibility API let’s just kinda cite George Berkeleyand say that:

“being visible” is being perceived.

关于javascript - 使用 ALT+TAB 切换程序/窗口或单击任务栏时不会触发 visibilitychange 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28993157/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com