JS实现进入站内新页面时bgm不中断
Admin Lv3

上一个版本切换页面时bgm会因为页面元素重置而中断并且丢失进度,用户需要手动重播,体验十分糟糕…

用户离开页面前使用localStorage存储bgm状态

1
2
3
4
5
6
7
8
9
10
const bgmPlayer = document.querySelector("...");
window.addEventListener('unload', () => {
const bgmState = {
currentTime: bgmPlayer.currentTime,
isPlaying: !bgmPlayer.paused
}u;
localStorage.setItem('bgmState', JSON.stringify(bgmState));

console.log(`bgm state saved, currentTime: ${bgmPlayer.currentTime}, isPlaying: ${bgmPlayer.isPlaying}`);
});

用户进入界面时恢复状态

1
2
3
4
5
6
7
8
9
10
const savedState = localStorage.getItem('bgmState');
if (savedState) {
const { currentTime, isPlaying } = JSON.parse(savedState);
bgmPlayer.currentTime = currentTime;
if (isPlaying) {
bgmPlayer.play();
}

console.log(`bgm state restored, currentTime: ${bgmPlayer.currentTime}, isPlaying: ${bgmPlayer.isPlaying}`);
}

浏览器问题

  • 某些浏览器例如Firefox会禁止bgm在新页面时自动播放,需要先在URL栏解除相关限制