Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Track navigation in iframe

Suppose that I have an iframe in my HTML page.

<html>
<body> 
This is my page
<button> Button </button>
<iframe src="www.example.com"></iframe>
</body>
</html>

So the user can click on links on the page www.example.com in the iframe. Is it possible to use JavaScript to track what links the user navigate to, and then when the user clicks Button, send those links to my server?

like image 264
Mika H. Avatar asked Nov 14 '25 16:11

Mika H.


1 Answers

You will not be able to track events in the iFrame from the page that hosts the iFrame. You could potentially track navigation from within the iFramed page and then sending the URL information to the parent page using window.postMessage. This would require that you have control of the pages inside the iFrame and you would only be able to track the clicks on pages you control and that are properly set up to send postmessages to the parent.

You can read more about [window.postMessage]following this link. A caveat is that some older browsers (IE7) don't support postMessage so you could use a library like Window postMessage plugin, which uses window.location.hash polling for those browsers. I have used this library previously and have had success with it.

like image 162
David Andrus Avatar answered Nov 17 '25 08:11

David Andrus