0

I try for two days to find a good answer but without success.

How can I run JavaScript DOM events in iFrame?

My goal is to collect data like onMouseMove on iFrame and retrieve this data.

For example:

When I recognized I'm in iFrame then I need to fire DOM events and collecting the data from the DOM events and retrieve the data to the parent page.

There are no cross-domain issues.

If anyone has a good explanation it will be great, because I want to understand perfectly how it's done.

Thanks In advance for all the answers.

Gavriel
  • 51
  • 5
  • Possible Duplicate. Please see -> https://stackoverflow.com/questions/364952/jquery-javascript-accessing-contents-of-an-iframe – daddygames Mar 06 '19 at 16:44
  • You have to try something, then we can tell you any problems with it. Otherwise, we don't know which part you're having trouble with. You should never ask someone to write it for you at SO – Ruan Mendes Mar 06 '19 at 17:25

1 Answers1

0

Maybe something like this?

const receiver = document.getElementById('receiver').contentWindow; // this is your iframe

receiver.addEventListener('mousemove', () => {
  // Do something
});
Mark
  • 1,610
  • 1
  • 14
  • 27
  • What is the 'message' in the 'addEventListener' and what is the 'typeName'? Thanks. – Gavriel Mar 06 '19 at 17:00
  • I updated my answer with a more simple approach. If this doesn't work I can help explain my last solution – Mark Mar 06 '19 at 17:01
  • The event name is `mousemove`, the iframe is not where you should register listeners, but on the [contentWindow](https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/contentWindow) – Ruan Mendes Mar 06 '19 at 17:26
  • Hi Mark, first of all, thanks, a second I want to tell what I understand. When The page finish loading I want to check each time the mouse moving if it's inside the iFrame or not (I do it by this condition --> window.location!=window.parent.location). If the mouse is inside the iFrame I add an event listener and then collect all my relevant data, I can save the data in a global object array. do you this is correct? just the way I thinking, because tomorrow I need to explain at work how theoretically how it's work. – Gavriel Mar 06 '19 at 22:03
  • The 'mousemove' event listener on the iframe like my code states would fire an event when the mouse is moved inside of the iframe. You could do all of your tracking from inside of this theoretically. – Mark Mar 06 '19 at 22:34
  • Feel free to select my answer as correct if this worked for you. Thanks! – Mark Mar 07 '19 at 14:21