Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
70
rated 0 times [  76] [ 6]  / answers: 1 / hits: 22935  / 9 Years ago, sun, december 20, 2015, 12:00:00

Is it possible to detect current page is in alt-tab?
This code works only if a new tab in browser is opened:



(function() {
var hidden = hidden;

// Standards:
if (hidden in document)
document.addEventListener(visibilitychange, onchange);
else if ((hidden = mozHidden) in document)
document.addEventListener(mozvisibilitychange, onchange);
else if ((hidden = webkitHidden) in document)
document.addEventListener(webkitvisibilitychange, onchange);
else if ((hidden = msHidden) in document)
document.addEventListener(msvisibilitychange, onchange);
// IE 9 and lower:
else if (onfocusin in document)
document.onfocusin = document.onfocusout = onchange;
// All others:
else
window.onpageshow = window.onpagehide
= window.onfocus = window.onblur = onchange;

function onchange (evt) {
var v = visible, h = hidden,
evtMap = {
focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h
};

evt = evt || window.event;
if (evt.type in evtMap)
document.body.className = evtMap[evt.type];
else
document.body.className = this[hidden] ? hidden : visible;
//console.log(this[hidden] ? hidden : visible);
}

// set the initial state (but only if browser supports the Page Visibility API)
if( document[hidden] !== undefined )
onchange({type: document[hidden] ? blur : focus});
})();


But this code does detect neither new window of the browser nor alt-tab into any other programm. Is it possible to detect it? Or in jQuery?



EDIT
New page means Ctrl(cmd)+N (new window) hotkey. The code above can not detect this. Alt(cmd)+tab to another program - impossible to detect too.
The code above can only detect Ctrl(cmd)+T (new tab)



EDIT
I want to detect when a user return to my site from another application. That is, if a user closes any tab (e.g., by Ctrl+W) and returns to my site I can detect this action using the script above. But if a user returns to my site from another application (e.g., by Alt+Tab) the script doesn't work because window.onfocus will not be fired! That is,



 window.onpageshow =
window.onpagehide = window.onfocus = window.onblur


doesn't work for Alt+Tab action. Is it more clear?


More From » jquery

 Answers
237

You can simply use the onfocus event on window, like in:



window.onfocus = function() {
console.log('Got focus');
}


If needed, you can also use onblur for a more acute handling.


[#64003] Thursday, December 17, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
breap

Total Points: 606
Total Questions: 96
Total Answers: 108

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
breap questions
Thu, Jun 24, 21, 00:00, 3 Years ago
Wed, Mar 18, 20, 00:00, 4 Years ago
Mon, Oct 7, 19, 00:00, 5 Years ago
;