J. Kovacevic
J. Kovacevic

Reputation: 193

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 {
    // ???
}

Upvotes: 5

Views: 2398

Answers (2)

pseudosavant
pseudosavant

Reputation: 7244

If you control both the parent and the iframe pages' content then you could use postMessage to pass the parent's onfocus event into the iframe.

Here is an example:

<iframe> content:

<!doctype html>
<html>
    <head>
    <script>
        // Function to call when receiving a `postMessage`
        function listener(event){
            if (event.data === 'focus-event') {
                document.querySelector("body").innerHTML += '<h2>Parent is in focus</h2>';
            }
        };

        // `postMessage` event listener
        window.addEventListener('message', listener, false);
    </script>
    </head>
    <body>
        <h1>Child</h1>
    </body>
</html>;

Parent content:

window.addEventListener('focus', function(event){
    iframe.postMessage('focus-event', '*');
}, false);

This will make it so that every time the parent window receives a focus event it will post that message to the iframe.

Here is a JSBin example.

Upvotes: 1

ujeenator
ujeenator

Reputation: 28626

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');
    } 
})

Upvotes: 4

Related Questions