Skip to content

Instantly share code, notes, and snippets.

@johnny77221
Forked from cferdinandi/stop-video.js
Last active July 20, 2020 02:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save johnny77221/dd49fba94330e80a8fa1ad60dd0ce7a4 to your computer and use it in GitHub Desktop.
Save johnny77221/dd49fba94330e80a8fa1ad60dd0ce7a4 to your computer and use it in GitHub Desktop.
A simple method to stop YouTube, Vimeo, and HTML5 videos from playing.
/**
* Stop an iframe or HTML5 <video> from playing
* @param {Element} element The element that contains the video
*/
var stopVideo = function ( element ) {
element.querySelectorAll('iframe').forEach(function(iframe) {
if ( iframe.contentWindow ) { /* send stop to content */
stopVideo(iframe.contentWindow.document);
}
else { /* Cross Domain, resetting src is all we can do, and the iframe might fail loading same url */
var iframeSrc = iframe.src;
iframe.src = iframeSrc;
}
});
element.querySelectorAll('video').forEach(function(item) { item.pause(); });
element.querySelectorAll('audio').forEach(function(item) { item.pause(); });
};
// then call from top level document
stopVideo(document);
@Zeaphon
Copy link

Zeaphon commented Jun 2, 2019

Thanks a lot for the code! Do you have an example of using this for the closing of a modal window? (Basically stop a video when closing a modal). I tried a lot of things but am stuck on how to actually getting this to work as a novice in javascript and jquery.

@johnny77221
Copy link
Author

Sorry, didn't try that. if you can get the window then you can close by calling stopVideo(window.document)

@Luminicus
Copy link

Hy, i tryed to call the stopVideo(document); in a click-event for a button to pause all videos on page, but it doesn't work. Error on row 7 of the script. "iframe was not found". Any Idea? Thanks and best regards.

@johnny77221
Copy link
Author

johnny77221 commented Sep 25, 2019

aww... change the line 6 forEach(function(item) to forEach(function(iframe) should solve the problem
the correct var name in the foreach.
Updated to the gist, Thank you!

@MerantauWarrior
Copy link

it won't work with YouTube iframe.contentWindow.document - this won'r pass XSS

@johnny77221
Copy link
Author

To the best of my knowledge, if resetting iframe src does not work(iframe contains autoplay video), there is no way to do this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment