Avoid crashing when AudioContext is not available. (#5641)

#4942. We've also had a number of crash reports show up in our logs related to this. Typically we see "undefined is not a constructor" because of the `window.AudioContext || window.webkitAudioContext` returns `undefined`.
This commit is contained in:
Chad Burggraf 2022-10-20 19:13:20 -07:00 committed by GitHub
parent a8561cd798
commit 4d0b302802
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -5,17 +5,21 @@ import { showBadgeOnFavicon } from './faviconHelper';
export const initOnEvents = ['click', 'touchstart', 'keypress', 'keydown']; export const initOnEvents = ['click', 'touchstart', 'keypress', 'keydown'];
export const getAlertAudio = async (baseUrl = '', type = 'dashboard') => { export const getAlertAudio = async (baseUrl = '', type = 'dashboard') => {
const audioCtx = new (window.AudioContext || window.webkitAudioContext)(); const audioCtx = getAudioContext();
const playsound = audioBuffer => { const playsound = audioBuffer => {
window.playAudioAlert = () => { window.playAudioAlert = () => {
if (audioCtx) {
const source = audioCtx.createBufferSource(); const source = audioCtx.createBufferSource();
source.buffer = audioBuffer; source.buffer = audioBuffer;
source.connect(audioCtx.destination); source.connect(audioCtx.destination);
source.loop = false; source.loop = false;
source.start(); source.start();
}
}; };
}; };
if (audioCtx) {
const resourceUrl = `${baseUrl}/audio/${type}/ding.mp3`; const resourceUrl = `${baseUrl}/audio/${type}/ding.mp3`;
const audioRequest = new Request(resourceUrl); const audioRequest = new Request(resourceUrl);
@ -28,6 +32,19 @@ export const getAlertAudio = async (baseUrl = '', type = 'dashboard') => {
.catch(() => { .catch(() => {
// error // error
}); });
}
};
export const getAudioContext = () => {
let audioCtx;
try {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
} catch {
// AudioContext is not available.
}
return audioCtx;
}; };
export const notificationEnabled = (enableAudioAlerts, id, userId) => { export const notificationEnabled = (enableAudioAlerts, id, userId) => {