justinribeiro / lite-youtube

The fastest little YouTube web component on this side of the internet. The shadow dom web component version of Paul's lite-youtube-embed.
https://www.npmjs.com/package/@justinribeiro/lite-youtube
MIT License
948 stars 70 forks source link

Add method for IFRAME postmessage #18

Closed faxenoff closed 2 years ago

faxenoff commented 4 years ago

With lite-youtube we out of control. Please add proxy method for send iframe postmessage

Original postmessage iframe.contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*');

Lite postmessage (something like this) [lite-youtube.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*');

p.s. listener from iframe would be nice, too.

radum commented 2 years ago

I ended up forking and doing it myself. But I admit would be a nice addition to have this built in.

justinribeiro commented 2 years ago

If you want to send the iframe a postmessage, you don't really need to do anything other pull the DOM reference in the shadow root after load (as available within v1.1.0 release):

document.addEventListener('liteYoutubeIframeLoaded', (event) => {
  // event.detail.videoId tells you which one it was

  // Give your lite-youtube an ID, and since there is only ever one iframe, 
  // you know the iframe is in the ShadowRoot once the event is thrown
  const iframe = document.querySelector(`#test-${event.detail.videoId}`).shadowRoot.querySelector('iframe');

  // send it a post message
  iframe.contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*');
}, false);