2

I am creating a chrome extension that automatically pauses the youtube video when I switch to another tab if the tab I am switching to is also youtube playing another video. I am looking for ways to have at least play/pause control over the native youtube player. All I could find on the internet after desperately searching is related to youtube iframe or embedding, like this one.

Is there any way I can achieve this by having direct control over the youtube player object or some other html5 browser features with javascript?

Regards.

Malem
  • 33
  • 7

1 Answers1

2

This is very simple on youtube video page.

Try this simple js code:

var video = document.querySelector("video");
if (video.paused){video.play();} else {video.pause();}

But for embedded Youtube videos you may want to review through the Youtube JavaScript API Reference docs. Read this for more details: https://stackoverflow.com/a/15165166/1225070

For html5 Videos.

Try this:

var vid = document.getElementById("myVideo");

function playVid() {
    vid.play();
}

function pauseVid() {
    vid.pause();
}
Aefits
  • 3,399
  • 6
  • 28
  • 46
  • The js code works and that's exactly what I wanted. I just couldn't get it since yesterday. Thank you very much, Sir. – Malem Feb 26 '18 at 10:22
  • Just did. But I can't upvote because of lack of reputation points. This is my first question on stackoverflow :) Thank you. – Malem Feb 26 '18 at 10:38
  • Great, and its fine! – Aefits Feb 26 '18 at 10:43
  • @elegant-user is there somewhere you can see how to perform other functions on the youtube page itself? Such as playing the next or previous video? – atman Jan 25 '21 at 18:55