P
P
Pavel Pavel2020-04-27 00:00:50
JavaScript
Pavel Pavel, 2020-04-27 00:00:50

How to correctly change the JS code so that Google Chrome does not give an error?

There is some code that assumes that an internet stream (audio) will automatically play when a web page is opened, however, an Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first error occurs.

Code snippet:

audioObjectExemplar.prototype = Object.create(audioObject.prototype);

audioObjectExemplar.prototype.setAudioPlay = function()
{
  if (this.audioClass != ''){
    document.getElementById(this.audioClass).className = this.audioClassName + ' active';	
  }
  document.getElementById(this.audioValue).load();
  document.getElementById(this.audioValue).play();
  this.audioState = 1;
}


The error lies in this line: How to fix it? document.getElementById(this.audioValue).play();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Proskurin, 2020-04-27
@pavelzabavin

This is the autoplay policy in chrome (other browsers also have it, but with their own characteristics). Chrome prevents audio from playing automatically if playback was triggered by a non-user action. This code needs to be called on click. Read more here https://developers.google.com/web/updates/2017/09/...
I think it's a very bad idea to turn on the sound when entering the page, it really infuriates users, which is why this policy was introduced by browsers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question