'How To Use 'beforeunload' to Capture Iframe Click?

I am trying to build a code that does a request when a cross-origin iframe is clicked and it directs the main window to a new page.

Since it's impossible to directly tap into Iframe click events, I thought of the following conditions as necessary:

  • page unload event occurs
  • the window is out of focus

Page unload (As far as I know) happens only when the current url is directed to some other url.

Now, this unload could happen by clicking any link. To restrict it to Iframes, I added the condition of window being out of focus.


addEventListener('beforeunload',(event) =>{
    if(!(document.hasFocus())){
        // Do Something
    }
});

My question is, are their any limitations to this approach? If yes, then please suggest some more conditions to make it as close to reality.

For those of you, who are curious: I want to track clicks on Google AdSense Iframes on my website.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source