JS 实现进入站内新页面时 BGM 不中断
营长 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栏解除相关限制
 评论