Using Tampermonkey, I have set up a script that monitors a webpage and alerts me whenever a set of conditions are met.
It works fine as long as the page has focus and being interacted with which is not the point of the script. It is meant to monitor the page while in background (open tab but not selected).
It seems to be due to the Chrome's Autoplay policy
as explained by the console's warning:
The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page. https://developer.chrome.com/blog/autoplay/#webaudio
Is there anyway to bypass this limitation?
Otherwise, feel free to suggest any other way to achieve the following: In Tampermonkey, start an audio alarm on demand whenever a given condition is met on a given page. The page is opened but has no focus necessarily.
Working snippet:
let audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const url = 'https://assets.mixkit.co/active_storage/sfx/1005/1005.wav';
function playAlarm() {
GM.xmlHttpRequest({
method: "GET",
url: url,
responseType: 'arraybuffer',
onload: function(response) {
let playsound = (audioBuffer) => {
let source = audioCtx.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioCtx.destination);
source.loop = false;
source.start();
// recursive call!
setTimeout(function () {
playsound(audioBuffer);
}, 10000 + Math.random()*2500);
};
audioCtx.decodeAudioData(response.response).then(playsound);
}
});
}