How to capture onclick within an iFrame for embedded YouTube video?

15,023

Solution 1

Everybody had great feedback. Thanks for all who posted. After trying some hacks the bottom line is that trapping the click event is not natively supported via html or javascript.

The best artifact and cleanest solution that I have found is here.

Solution 2

You can't, I believe. That would be a security risk. If you mainly want to do tracking and whatnot, you would probably be best off doing something like adding an image/button in the place of the video that the user clicks, causing the video to appear.

Edit: This solution may work too; I'm not sure if it'll work for iframes that aren't on the same domain.

Solution 3

window.postMessage could help. But you should have an access to source code of the page you're rendering in iframe. So in case of embedding of youtube video, you probably can't deal with this.

Share:
15,023
genxgeek
Author by

genxgeek

20+ years of full-stack development and technical project management delivering global software solutions across manufacturing, consumer products and business analytics.

Updated on June 09, 2022

Comments

  • genxgeek
    genxgeek almost 2 years

    I have an iFrame that displays an embedded youtube video.

    <iframe width="560" height="315" src="http://www.youtube.com/embed/xxx" frameborder="0" allowfullscreen></iframe>
    

    What I would like to do is somehow capture the click event when the user clicks the you tube video so that I can call an http://myserver.com/dostuff rest api to update an external server counter tracking the number of clicks and of course allow the video to play as expected.

    Any information would be greatly appreciated.