Reputation: 704
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:
Upvotes: 4
Views: 3232
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
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 besuspended
,running
, orclosed
.When working with an
AudioContext
, if you create the audio context from inside aclick
event thestate
should automatically be set torunning
.
Source: Web Audio API best practices
Upvotes: 3