Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Failed to execute 'play' on 'HTMLMediaElement': Illegal invocation

Just a simple problem.

I want to assign a HTMLMediaElement method to variable.

// html part
<video id="player" ... />

// js part
const video = document.querySelector('#player')
const play = video.play

video.play() // works!

play() // error!

Uncaught (in promise) TypeError: Failed to execute 'play' on 'HTMLMediaElement': Illegal invocation

anyone knows why this error happened?

like image 698
WendellLiu Avatar asked May 22 '17 09:05

WendellLiu


1 Answers

The native DOM implementation of HTMLMediaElement.play requires this to be bound to an HTMLMediaElement.

video.play() works because the this value is bound to video. play() doesn't work because the this value is now bound to something else (maybe window?).

You can either call it using:

const video = document.querySelector('#video');
play = video.play;

play.call(video);
<video id="video" src="http://vjs.zencdn.net/v/oceans.mp4" controls>

or "save it for later" using bind:

const video = document.querySelector('#video');
play = video.play.bind(video);

play();
<video id="video" src="http://vjs.zencdn.net/v/oceans.mp4" controls>
like image 127
evolutionxbox Avatar answered Nov 19 '22 22:11

evolutionxbox