如何在 chrome extension 裡播放音樂:
- Chrome Extension V3 offscreen audio not working due to “Receiving end does not exist.”
https://stackoverflow.com/questions/78110557/chrome-extension-v3-offscreen-audio-not-working-due-to-receiving-end-does-not-e
附註:上面網址裡附的範例,有 typo 錯誤,message
應該改為msg
- Play audio from background script in chrome extention manifest v3
https://stackoverflow.com/questions/67437180/play-audio-from-background-script-in-chrome-extention-manifest-v3
程式碼:
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();
}