Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect moving to a new tab in Mobile Safari

I have a series of pages that open popups (new tabs in Mobile Safari.) Each of these popups needs to know when they are the focused or not. On desktops, we use window.onblur and window.onfocus to drive this behavior. However, none of these events work on iPad. I also tried window.onpageshow and window.onpagehide which don't seem to fire at the right times either. I have a test HTML file:

<html>
<head>
<script language="javascript">
console.log('Hello');
window.onblur = function(e) { console.log('blur'); };
window.onfocus = function(e) { console.log('focus'); };
window.onpagehide = function(e) { console.log('pagehide'); };
window.onpageshow = function(e) { console.log('pageshow'); };
</script>
</head>
<body>
<a href="http://www.google.com" target="_blank">Click Me</a>
</body>
</html>

In theory, when you click 'Click Me', you should get a blur event when the new window appears. But this doesn't happen on Mobile Safari. onpagehide and onpageshow show no love either, they only help for detecting when you're about to close the tab.

How can I get the behavior I'm looking for in Mobile Safari? Is it possible at all?

like image 791
joshk0 Avatar asked Jun 18 '12 14:06

joshk0


2 Answers

Try this: https://gist.github.com/1122546

It's a Visibilty API polyfill. Should do the trick.

like image 70
Bruno Avatar answered Sep 22 '22 06:09

Bruno


I don't think that onblur can be detected, but this is a code to detect onfocus:

var timestamp=new Date().getTime();
function checkResume()
{
    var current=new Date().getTime();
    if(current-timestamp>5000)
    {
        var event=document.createEvent("Events");
        event.initEvent("focus",true,true);
        document.dispatchEvent(event);
    }
    timestamp=current;
}
window.setInterval(checkResume,50);

Then you just write:

document.addEventListener("focus",function()
{
    alert("Focus detected");
},false);
like image 41
Mageek Avatar answered Sep 25 '22 06:09

Mageek