New Solution With Offscreen Documents
It's not currently possible to play or capture media directly in service workers because they don't have access to DOM APIs.
Offscreen documents is out for Chrome version 109, so here is my solution based on the api test file from Chromium. Because code on an offscreen document has access to the needed API, you need to open one and use message passing to play the sound from there. This solution is far more elegant than the older one, which utilized a visible popup window for the same reason.
To play a sound in the service worker, call the playSound()
function with the appropriate parameters as shown below.
If you don't play sounds for 30 seconds, the offscreen document will be closed automatically because of the "lifetime enforcement".
manifest.json
...
"permissions": ["offscreen"]
...
background.js
/**
* Plays audio files from extension service workers
* @param {string} source - path of the audio file
* @param {number} volume - volume of the playback
*/
async function playSound(source = 'default.wav', volume = 1) {
await createOffscreen();
await chrome.runtime.sendMessage({ play: { source, volume } });
}
// Create the offscreen document if it doesn't already exist
async function createOffscreen() {
if (await chrome.offscreen.hasDocument()) return;
await chrome.offscreen.createDocument({
url: 'offscreen.html',
reasons: ['AUDIO_PLAYBACK'],
justification: 'testing' // details for using the API
});
}
offscreen.html
<script src="offscreen.js"></script>
offscreen.js
// Listen for messages from the extension
chrome.runtime.onMessage.addListener(msg => {
if ('play' in msg) playAudio(msg.play);
});
// Play sound with access to DOM APIs
function playAudio({ source, volume }) {
const audio = new Audio(source);
audio.volume = volume;
audio.play();
}
Note: The offscreen API is relatively new, so some users might not yet have the minimum required version of Chrome (109) to support it. If you care about such users, you could use the older solution as a polyfill by checking if chrome.offscreen
is undefined.
One last thing: You should update the justification property for creating the offscreen document. It's required, but not yet used. The documentation says the following:
justification
A developer-provided string that explains, in more detail, the need for the background context. The user agent may use this in display to the user.
Original answer
As written in the official documentation:
It's not currently possible to play or capture media directly in a
service worker. In order for a Manifest V3 extension to leverage the
web's media playback and capture capabilities, the extension will need
to create a window environment using either chrome.windows.create() or
chrome.tabs.create(). Once created, the extension can use message
passing to coordinate between the playback document and service
worker.
Until they do something about this, (hopefully, they eventually will - considering the usage of "currently" in their article) here is a quick workaround:
audio.html
<link href='icon.png' rel='icon' type='image/x-icon'>
<title>Notification</title>
<script src="audio.js"></script>
<style> :root { color-scheme: light dark }</style>
audio.js
resizeTo(0, 0);
onload = () => {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
let audio = new Audio(urlParams.get('src'));
audio.volume = urlParams.get('volume');
audio.play();
setTimeout(close, urlParams.get('length'));
}
background.js
(the service worker)
function playSound() {
let url = chrome.runtime.getURL('audio.html');
// set this string dynamically in your code, this is just an example
// this will play success.wav at half the volume and close the popup after a second
url += '?volume=0.5&src=success.wav&length=1000';
chrome.windows.create({
type: 'popup',
focused: true,
top: 1,
left: 1,
height: 1,
width: 1,
url,
})
}
Once playSound()
gets called, it will create a popup that will play the sound. It's a good idea to set the popup's icon to your extension's icon with the <link>
tag so your users will know where the popup came from.
Note that audio.js
must be linked from a separate file. Otherwise, you would receive an inline script policy violation error.
Further ideas
If you play sounds while sending toast notifications with the chrome.notifications API, You might want to move your popup behind the notification. An easy way to do that is to create the popup in the bottom right corner with: top: 99999, left: 99999
Then in your javascript: moveTo(window.screenX - 100, window.screenY);
Alternatively, you could turn the popup itself into the toast notification.
Update #1
Seems like there is some work being done on a feature called offscreen documents for MV3. With this new API, extensions will be able to open limited, offscreen documents having access to DOM APIs.
More info is in the proposal.
And here you can track its development.
However, this won't be the final solution. As stated in the proposal, long term, Chromium intends to support many of these capabilities directly within extension service workers.