WendellLiu
WendellLiu

Reputation: 317

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?

Upvotes: 9

Views: 4278

Answers (1)

evolutionxbox
evolutionxbox

Reputation: 4122

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>

Upvotes: 11

Related Questions