zachThePerson
zachThePerson

Reputation: 704

Javascript: What counts as "User interacting with webpage?"

I'm trying to build a chrome extension that plays an audio file when a value on the page changes to alert the user that it has changed. Sometimes it works, but other times it says that the "play()" method was not allowed because "The user has not interacted with the webpage."

It will usually work when the webpage is first loaded, but when navigated away within the same site it will often throw this error.

This question can be split into two smaller questions:

  1. What counts as a "User interaction," in Chrome? I can't seem to find any information on this.
  2. Is there any way to check using Javascript if the "User interaction," flag has been set?

Upvotes: 4

Views: 3232

Answers (2)

zachThePerson
zachThePerson

Reputation: 704

Ok, so I figured it out.

The extension now appends a button to the top of the page called "Activate." When it's clicked, it calls:

function checkVal(){
    if ( /*check if the value has changed*/ ){
        let myAudio = new Audio('my_audio.mp3');
        myAudio.play();
    }
    else{
        setTimeout(checkVal, 5);
    }
}

It's a little hacky, but it works for my purposes.

Upvotes: 1

Sean
Sean

Reputation: 8064

This is related to the Web Audio API. From the Mozilla Web Docs:

Browsers have started to implement an autoplay policy, which in general can be summed up as:

"Create or resume context from inside a user gesture".

This is to prevent webpages from blaring audio on page load without interaction from the user. The docs go on to state:

But what does that mean in practice? A user gesture has been interpreted to mean a user-initiated event, normally a click event. Browser vendors decided that Web Audio contexts should not be allowed to automatically play audio; they should instead be started by a user. This is because autoplaying audio can be really annoying and obtrusive. But how do we handle this?

When you create an audio context (either offline or online) it is created with a state, which can be suspended, running, or closed.

When working with an AudioContext, if you create the audio context from inside a click event the state should automatically be set to running.

Source: Web Audio API best practices

Upvotes: 3

Related Questions