Unable to play video using the play() method in Video.js player instance

I am trying to start playing a video.js player instance programmatically by using the play() method on it.

The markup for the player is as follows:

<video-js id   ="some-player-id"
          src  ="https://vjs.zencdn.net/v/oceans.mp4"
          class="VideoPlayer">
</video-js>

According to the documentation, I should be able to create the player using the element's id and then call play() to start playback...

// Initialize player instance
const player = videojs.getPlayer("some-player-id");

// Start playback when ready
player.ready(function() {
  player.play()
});

However, I am facing some issues with this approach and would like to understand why. Please refer to the attached snippet for more information.

// Initialize player instance
const player = videojs("some-player-id");

// Start playback when ready
player.ready(function() {
  player.play();
});
<link href="https://vjs.zencdn.net/7.20.1/video-js.css" rel="stylesheet"/>

<div class="VideoPlayer">
  <video-js id   ="some-player-id" 
            src  ="https://vjs.zencdn.net/v/oceans.mp4" 
            class="VideoPlayer__videoJs">
  </video-js>
</div>

<script src="https://vjs.zencdn.net/7.20.1/video.min.js"></script>

Answer №1

If you happen to be using the Chrome browser, it could be the culprit in this situation. As stated by their policy, the browser may interfere and halt playback in specific scenarios.

Because the play() method returns a promise, we can handle any errors by attaching a catch() method.

player.play().catch(error => console.log(error));

If autoplay is prevented by the browser, an error message similar to the following should be expected.

DOMException: play() failed because the user didn't interact with the document first.

An effective approach is to always mute the video before initiating playback.

player.muted(true);
player.play();

However, what happens if we unmute the videos after they start playing? The result will be the video pausing after the initial muted period.

player.muted(false);

// OR

setTimeout(() => {
  player.muted(false);
}, 3000);

In my opinion, the most reliable method for playing videos with sound is to have a backup plan in place, such as displaying a large play button or similar element when autoplay fails.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Newbie in JavaScript seeking help with JSON indexing: What could be causing my script using (for ... in) to fail?

Not being a seasoned Javascript coder or very familiar with JSON, my approach may seem naive. Any recommendations for better solutions are appreciated. Below is the code I've written: <!DOCTYPE html> <html> <head> <script& ...

Error occurs with Nodemon application crashing while executing Gulp command

Recently, my React app started crashing whenever I run the Gulp command. Oddly enough, it was functioning perfectly just a few hours ago. The only change I made was updating my node version from 6.2.1 to 6.2.2 in order to deploy the application on Azure. H ...

`In AngularJS, the same URL ('/') can display different templates depending on the user's login status.`

What is the most effective way to configure routing and templates in AngularJS to display a distinct front end and login area for visitors, while presenting a dashboard to logged-in users all on the same base URL ('/')? These two pages have comp ...

What is the best way to display JSON response as code instead of a string in AngularJS?

When retrieving my article from the database as a JSON object, I encounter an issue with the body content. The HTML codes in the body are displayed as strings within double quotation marks by AngularJS. How can I resolve this? Angular controller snippet: ...

Managing JavaScript expiration time in API responses

Seeking help with a JavaScript API I'm new to. The response I received contains a timestamp, which seems like it's in milliseconds. I want to format this time for a countdown but I'm not sure what these milliseconds are referring to. I know ...

Tips for JavaScript validation before submitting a form in Zend framework

I created this JavaScript code for form validation, but it is also submitting data to the database even when the validation fails. I need help in modifying the code so that it only submits the data if the conditions are met. Below is the HTML code: <f ...

Utilizing Vue.js to display raw HTML content in elements.io table

I am trying to display HTML data in a table using Vue.js. new Vue({ el: "#app", data: { todos: [ { text: "<p>Learn JavaScript</p>", done: false }, { text: "<p>Learn Vue</p>", done: false ...

Activate when every single pixel within an element is see-through

I've designed a web page that includes two canvas elements stacked on top of each other. The purpose of this setup is to allow me to "erase" the top canvas and reveal an image loaded into the bottom canvas. So far, this functionality has been working ...

Utilizing Jquery to enhance slide image transitions with navigational links

As a newcomer to jQuery, I am attempting to create a slider using jQuery. Here is the script I have so far: $(function() { var bgCounter = 0, text = [ 'some html code here', 'some html code here', 'some ...

HTML & jQuery guide: The correct way to execute a function on an anchor element (compatible across all browsers)

My webpage contains several anchor tags that are used to trigger a function. Although everything is functioning correctly, I am unsure of the best way to ensure cross-browser compatibility, as different methods can be found online. I have opted to use jQu ...

Dynamic Interactive Content with AJAX

Imagine if all the forms in your application followed this structure: <div id="result_messages"></div> <form action="/action"> <!-- all the form --> </form> Here's an example of what a submit button for this form might ...

Exploring the source code of NPM public and private packages within the node_modules directory

As someone who is new to javascript development, I want to create a private npm package that cannot be accessed by users. However, I have noticed that I can still view the code of other npm packages labeled as closed-source by entering their node_modules s ...

Is it necessary to clear out older node.js sessions that are saved in a database?

After incorporating a database session storage for my node application, I noticed that abandoned sessions could potentially linger in the database indefinitely if a user never returns to the application or clears their cookies. Would it be advisable for m ...

Error: Attempting to access a property of an undefined value (referencing '8') was unsuccessful

Hello everyone, I am new to posting and identify as a junior Frontend developer. I'm encountering a confusing issue with the InputLabel from Material UI (ver. 5) on a specific section of the website I'm working on. On the homepage, I successfully ...

Angular library modules for node packages

After developing my latest library, I noticed some red underlines: https://i.stack.imgur.com/ffAjI.png In this package, I plan to incorporate other npm packages like ionic and crypto. I attempted to update the package.json within the library: { "name ...

Tips for ensuring a module.export function completes its request before assigning the returned value to a variable in another JavaScript file

Within my Node.js application, I am utilizing two JS files. One of these files, latlng.js, contains the following code: async function getPlaceDetails(input) { var locationUrl = 'https://www.google.com'; request(locationUrl, (error, respo ...

Using SailsJS to populate attributes transmitted through socket.io's publishUpdate event

Utilizing the built-in socket capabilities of SailsJS has proved to be quite effective for me so far. However, I've encountered a challenge that I haven't been able to find any information on. In my model, I have set it up to populate certain at ...

Filtering in JavaScript arrays based on conditions that are not related to the elements in the array

Consider the following code snippet: var numbersArray = [1, 3, 6, 8, 11]; var returnedArray = numbersArray.filter(function(number) { const condition = false // or true sometimes return number > 7 && condition ; }); console.log(returnedArra ...

When users visit my contact HTML page, they are redirected to the contact PHP page, but unfortunately, the email is

I am currently facing an issue with my contact form. After filling out the form and hitting the "send" button, it redirects to the contact.php page but fails to send an email or work as intended. Can someone please assist me and identify what's causin ...

Generating PDF files from HTML documents using Angular

I am currently working on an Angular 11 application and I have a specific requirement to download a PDF file from a given HTML content. The challenge is that the HTML content exists independent of my Angular app and looks something like this: < ...