Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access onfocus event from iframe (cross-origin)?

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 {
    // ???
}
like image 494
J. Kovacevic Avatar asked Dec 01 '15 10:12

J. Kovacevic


1 Answers

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');
    } 
})
like image 195
ujeenator Avatar answered Nov 14 '22 06:11

ujeenator