NoSleep.js icon indicating copy to clipboard operation
NoSleep.js copied to clipboard

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

Open MuhammadRahman-awin opened this issue 3 years ago • 4 comments

  • Device Name: Linux OS
  • Device Version: 20 LTS
  • Browser Name: chrome browser
  • Browser Version: Version 100.0.4896.75 (Official Build) (64-bit)
  • NoSleep.js Version: 0.12

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 avatar Apr 20 '22 23:04 MuhammadRahman-awin

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

MuhammadRahman-awin avatar Apr 21 '22 00:04 MuhammadRahman-awin

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.

MuhammadRahman-awin avatar Apr 21 '22 00:04 MuhammadRahman-awin

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);
      ...
}

CorentinChauvin avatar Dec 21 '22 13:12 CorentinChauvin