Home > front end >  Capturing mousedown event on div with iframe child
Capturing mousedown event on div with iframe child

Time:06-25

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 >
<a href="/" >Test</a>
</div>

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

CodePudding user response:

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).

CodePudding user response:

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 >
  <iframe id="testiframe" src="https://www.google.com/" ></iframe>
</div>

CodePudding user response:

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?

  • Related