0

I'm trying to capture the mouse down event for the div containing the iframe. Is there any way to do it? It seems that the iframe is capturing the event and the mousedown event is not triggered for the div.

jQuery(".test").on("mousedown", ()=> console.log("Test"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test">
<a href="/" >Test</a>
</div>

<div class="test">
<iframe src="https://www.google.com/" ></iframe>
</div>

3 Answers3

0

As far as i know, the only way you will be able to interact with iframe-content via javascript (and css aswell) is, if the scope of the domain is the same. Example-Demo

Any Cross-Domain interaction nowadays requires a CORS-configuration to allow for interaction between the different domains.

For that reason i would argue, that what you are trying to achieve is not really possible anymore (except if you are in control of both domains).

Christoph Kern
  • 419
  • 2
  • 7
  • I'm not trying to interact with the iframe, I'm trying to interact with the parent div. But is seems that the iframe is capturing the event. – Daniel Pérez Rodríguez Jun 24 '22 at 11:50
  • When the iframe content loads, everything within the iframe-container is not considered to be "your" website anymore. Therefore any javascript-interaction is not allowed, since that woud be an unauthenticated cross-domain-request. – Christoph Kern Jun 24 '22 at 11:59
  • 1
    Have a look at this [question](https://stackoverflow.com/questions/1609741/how-to-add-click-event-to-a-iframe-with-jquery) As mentioned in the comments of the top answer, your only way might be to use some sort of "hack" when you leave the realms of your own domain. Like putting and absolute positioned element above the iframe – Lapskaus Jun 24 '22 at 12:20
0

I managed to find a solution, not the best but it works for me

jQuery(window).on('blur', function() {
  if (document.activeElement === document.querySelector('iframe')) {
    console.log('clicked on iframe')
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="test">
  <iframe id="testiframe" src="https://www.google.com/" ></iframe>
</div>
-3

Since you are using jQuery, you can use the contents() method, so:

jQuery(".test").contents().on("mousedown", ()=> console.log("Test"))

However, it can be a bit sketchy to intercept a click to someone else's page!! What are you doing with the click?

Blunt Jackson
  • 616
  • 4
  • 17