user38208
user38208

Reputation: 1094

Detecting a click in an iframe

I understand that it is not possible to tell what the user is doing inside an iframe if it is cross domain. What I would like to do is if a link inside an iframe is clicked, a div appears on the page holding the actual iframe.

Is this actually possible?

Upvotes: 1

Views: 707

Answers (2)

David Bradshaw
David Bradshaw

Reputation: 13077

If you have access to both codebases. Then you can use the postMessage API to communicate between the iFrame and the parent page.

Upvotes: 0

Wiktor Bednarz
Wiktor Bednarz

Reputation: 1553

Assuming that you only control a page holding a frame and you just want to check if any link inside that frame was clicked, you can listen for frame's load event.

Obviously it's not 100% reliable. For starters, you don't know which link was clicked. It doesn't work for links to #hashes (on the same page). Finally, you cannot distinguish between page reload and address change.

Unfortunately, without access to the frame, there's nothing more you can do.

If, on the other hand, you control both frame's page and a page holding that frame (but they're on different domains), you can gain full control, as long as you conform to Same-origin policy.

Example

Here's an over–complicated (for looks :D) example:

var frame = document.querySelector('iframe'),
    indicator = document.querySelector('#frame-state'),
    ignoreFirstLoad = true,
    timeout = null;
    
frame.addEventListener('load', function() {
  if (ignoreFirstLoad) {
    ignoreFirstLoad = false;
    return;
  }
  
  // some link was clicked or frame was reloaded
  indicator.classList.add('loaded');
  clearTimeout(timeout);

  timeout = setTimeout(function() {
    indicator.classList.remove('loaded');
  }, 1000);
});
iframe {
  width: 100%;
}

#frame-state {
  opacity: 0;
  transition: opacity 2s;
  
  font-weight: bold;
}

#frame-state.loaded {
  opacity: 1;
  transition: opacity .2s;
}
<p>Click on any link inside the frame: <span id="frame-state">Loaded!</span></p>

<iframe src="https://en.m.wikipedia.org/"></iframe>

Upvotes: 3

Related Questions