Attach event listeners to different domain from current domain

I was working on some project where in I have a scenario as mentioned below

Parent domain :

Child domain :

For instance my parent domain is in my parent domain I have a button named capture on click of this button I am loading child domain which has a url in a new tab using javascript

Along with loading child domain url in new tab I am trying to attach eventlisteners to child domain from parent domain.

I am trying to find capture all click actions performed in child domain in parent domain.

I am aware of CORS but I would like to achieve this using javascript

Is it possible ? any pointers highly appreciated

Thanks in Advance

Answers 1

  • The browser will not let you directly access browser windows that contain pages from other domains in any way (for security reasons). So, you cannot directly add event listeners to any domain's page at all.

    What you are allowed to do is to have two pages cooperate (under the theory that if they are specifically cooperating together, then it must be OK security-wise). But, even in the cooperating case, you can't have page with domain A add event listeners into page with domain B. You just can't do it.

    You can use window.postMessage() to either send some sort of command to the other window and the other window has the then carry out the DOM action itself. Of you can send window.postMessage() to request some information from the other window and then the other window would have a listener for your specific request, would get that information and would send the data back. This structure obviously needs two completely cooperating pages. For security reasons you can (and should) restrict what domains you are willing to accept messages from. See the MDN doc for window.postMessage() for more details.

    As to your specific question:

    I am trying to find capture all click actions performed in child domain in parent domain.

    You can't do this from the parent domain. You could send a message from the parent domain to the child domain to ask the child domain to set up the requested click handlers on itself and then to window.postMessage() you data each time a click happens. The majority of work has to be done inside the child window with its own code.

Related Articles