0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Cerulean
  • 5,543
  • 9
  • 59
  • 111
  • _“So my thought was to grab the video tag inside the iframe”_ - you can not reach into an iframe, that loads its content from a different domain - the [Same Origin Policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) prevents that. – CBroe Jul 01 '20 at 13:48
  • 1
    _“but it seems to rely on knowing the IDs of the iFrames; the iFrames that we are getting don't have any ID.”_ - then set one …? After you inserted your CMS HTML into your document, loop over the iframes, assign an ID (something like `yt-vid-xy`, with the `xy` part being a counter) … and then initialize the YT Player API for each one afterwards, using that ID. – CBroe Jul 01 '20 at 13:50
  • @CBroe -- Sounds good. However now that I think about it, the solution I found will only work for YouTube videos through the YouTube API. Is there a general solution? – Cerulean Jul 01 '20 at 13:54

0 Answers0