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,29 +5,46 @@ import { showBadgeOnFavicon } from './faviconHelper';
export const initOnEvents = ['click', 'touchstart', 'keypress', 'keydown'];
export const getAlertAudio = async (baseUrl = '', type = 'dashboard') => {
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const audioCtx = getAudioContext();
const playsound = audioBuffer => {
window.playAudioAlert = () => {
const source = audioCtx.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioCtx.destination);
source.loop = false;
source.start();
if (audioCtx) {
const source = audioCtx.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioCtx.destination);
source.loop = false;
source.start();
}
};
};
const resourceUrl = `${baseUrl}/audio/${type}/ding.mp3`;
const audioRequest = new Request(resourceUrl);
if (audioCtx) {
const resourceUrl = `${baseUrl}/audio/${type}/ding.mp3`;
const audioRequest = new Request(resourceUrl);
fetch(audioRequest)
.then(response => response.arrayBuffer())
.then(buffer => {
audioCtx.decodeAudioData(buffer).then(playsound);
return new Promise(res => res());
})
.catch(() => {
// error
});
fetch(audioRequest)
.then(response => response.arrayBuffer())
.then(buffer => {
audioCtx.decodeAudioData(buffer).then(playsound);
return new Promise(res => res());
})
.catch(() => {
// 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) => {