I have html app that uses onfocus event. It's working perfectly when switching tabs of browser.
Now, when I load that app as an iframe in another html page, it's not working because the iframe is not focused when switching tabs. How to access onfocus event from iframe without modification of top level code.
The iframe and page that loads iframe are not from same origin.
if (!window.parent.frames.length) {
window.onfocus = function () {
// do smth
};
} else {
// ???
}
You can use HTML5 Visibility API. It allows you to detect when user leaves and returns to the tab.
At moment when I'm writing this post - this feature supported by 90% of browser: http://caniuse.com/#feat=pagevisibility
Sample code for iframe page:
document.addEventListener('visibilitychange', function(){
var time = new Date();
if (document.hidden) {
console.log(time + ' the user has left tab');
} else {
console.log(time + ' the user has returned to the tab');
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With