Ali
Ali

Reputation: 35

How to play notification audio file in Chrome WebExtension without user gesture?

I'm building a webextension for Google Chrome and I'm trying to implement a function that plays a sound effect to notify the user about updates on the background.js script.

    var sound = new Audio(browserContainer.runtime.getURL("audio/not.ogg"));
    sound.play();

The problem is that thanks to Chrome's policies, the audio cannot autoplay without some sort of user gesture. I receive the error "Uncaught (in promise) NotAllowedError: play() can only be initiated by a user gesture."

How can I force Chrome to autoplay the notification sound without a user gesture? I know it is possible, because I've seen other extensions do this, like "Checker Plus for Gmail"

Upvotes: 1

Views: 1434

Answers (1)

Iván Nokonoko
Iván Nokonoko

Reputation: 5118

You can try adding an audio HTML tag to the background page, like this:

manifest.json

"background":{"page":"background.html"}

background.html

<html>
<body>
    <audio id="mysound" preload="auto" src="audio/not.ogg"></audio>
    <script src="background.js"></script>
</body>
</html>

background.js

var sound = document.getElementById('mysound');
sound.play()

Upvotes: 2

Related Questions