We have a NextJS/React application that is receiving HTML from our CMS. That HTML is coming from a TinyMCE editor on our backend and can and will include various embeds, such as YouTube videos, other kinds of videos, podcasts, etc. We add the HTML to our React page using _dangerouslySetInnerHTML
. All works fine, except that we wish to add Google Analytics to the page, and thus want to add event listeners to the onplay
events of all embedded objects.
I've been researching for a while now to see how to add an onload event to a YouTube video, which seems to require more control of the HTML than we have. So my thought was to grab the video
tag inside the iframe
and add an onload
listener to that. This requires knowing when the iFrame has loaded. I got all of that to work, but am now told
SecurityError: Blocked a frame with origin "http://localhost:8080" from accessing a cross-origin frame.
when I try to access the video inside the Iframe.
I found this -- YouTube iframe API: how do I control an iframe player that's already in the HTML? -- but it relies on jQuery, which, as I understand it, doesn't play nice with React, so I'd like to avoid it.
It seems like this would be something that has been done before: add Google Analytics to embedded media, for example, listen to onplay
events on videos embedded inside iFrames, such as YouTube, inside a React app.
Edit
I found this interesting solution -- How to integrate Youtube Iframe api in reactjs solution -- but it seems to rely on knowing the IDs of the iFrames; the iFrames that we are getting don't have any ID.
Edit 2
As @cbroe points out below, I can add IDs to take advantage of the YouTube solution. However this solution uses the YouTube API. Is there a general solution applicable to all embeds?