richtr / NoSleep.js

Prevent display sleep and enable wake lock in any Android or iOS web browser.
MIT License
2.19k stars 379 forks source link

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

Open MuhammadRahman-awin opened 2 years ago

MuhammadRahman-awin commented 2 years ago

Expected Behavior

It should run the video muted so it does not throw a js error.

Actual Behavior

It throws a Js error "DOMException: play() failed because the user didn't interact with the document first"

Code

    var noSleep = new NoSleep();
    noSleep.enable();

How Do We Reproduce?

Use it on a blank page and check the console, please.

MuhammadRahman-awin commented 2 years ago

The error also has this helper link, hope that will be helpful. https://developer.chrome.com/blog/autoplay/

MuhammadRahman-awin commented 2 years ago

and I found this from SO where it says, the fix is to make the video Muted https://stackoverflow.com/questions/49930680/how-to-handle-uncaught-in-promise-domexception-play-failed-because-the-use

Appreciate your help.

CorentinChauvin commented 1 year ago

I believe I had the same issue (Firefox 108.1.0, Android 6).

Warning: Autoplay is only allowed when approved by the user, the site is activated by the user, or media is muted.
Error: Uncaught (in promise) DOMException: The play method is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

Solved it by adding this.noSleepVideo.muted = true; to have something like:

var NoSleep = function () {
  function NoSleep() {
    ...
    if (nativeWakeLock()) {
      ...
    } else if (oldIOS()) {
      this.noSleepTimer = null;
    } else {
      // Set up no sleep video element
      this.noSleepVideo = document.createElement("video");

      this.noSleepVideo.setAttribute("title", "No Sleep");
      this.noSleepVideo.setAttribute("playsinline", "");
      this.noSleepVideo.muted = true;  // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

      this._addSourceToVideo(this.noSleepVideo, "webm", webm);
      ...
}
MasterInQuestion commented 1 year ago

    See:     https://github.com/richtr/NoSleep.js/issues/53#issuecomment-443980576     https://github.com/richtr/NoSleep.js/issues/10