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

I have an html application that uses the onfocus event. It works great when switching browser tabs.

Now, when I load this application as an iframe to another html page, it does not work, because the iframe not focused when switching tabs. How to access onfocus event from iframe without changing top-level code .

iframe and the page loading the iframe are not from the same source.

 if (!window.parent.frames.length) { window.onfocus = function () { // do smth }; } else { // ??? } 
+5
source share
2 answers

You can use the HTML5 visibility API. This allows you to detect when the user is leaving and returning to the tab.

At the moment I write this post - this function is supported by 90% of the 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'); } }) 
+3
source

If you control the contents of the parent and the contents of the iframe, you can use postMessage to pass the parent onfocus event to 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 sure that every time the parent window receives a focus event, it sends this message to the iframe.

Here is an example of JSBin .

+1
source

Source: https://habr.com/ru/post/1237159/


All Articles