Answer the question
In order to leave comments, you need to log in
How to make the music not reset on reload / page transition?
I found a great thing - a radio script for the site . Works as it should, but resets on page transitions. How to avoid it? How to make the radio play constantly in the background when the user navigates the site?
Answer the question
In order to leave comments, you need to log in
Make the site look like a single page application.
To prevent reloads when switching between pages.
I would do it myself, just hang handlers on all links on the site and, when clicking on them, would cancel the transition and open the selected page inside an iframe with 100% width and height, without visible borders. There will be some analogue of ajax content loading. Of course, we must take into account that the radio inside the iframe is not started and the handlers inside the ifarme are also not set, then everything will be ok.
<audio id="music-player" src="/storage/files/music-1.mp3" loop></audio>
<script>
(function () {
const player = document.getElementById('music-player');
if (!player) return;
const toggle = document.getElementById('toggle-music');
if (screen.width < 1220) return;
if (!toggle) return;
let playing = false;
let firstPlay = true;
let iPos;
const KEY_MP_PAUSED = 'music-player-paused';
const KEY_MP_POSITION = 'music-player-position' + player.src;
const startPosition = parseFloat(localStorage.getItem(KEY_MP_POSITION));
const mpPaused = +localStorage.getItem(KEY_MP_PAUSED);
function enablePlay() {
if (firstPlay) {
firstPlay = false;
if (startPosition) player.currentTime = startPosition;
}
player.play();
toggle.classList.add('music-on');
}
function userClick() {
document.removeEventListener('click', userClick);
enablePlay();
}
if (!mpPaused) document.addEventListener('click', userClick);
function updateCurrentPosition() {
localStorage.setItem(KEY_MP_POSITION, player.currentTime.toString());
}
player.addEventListener('play', e => {
playing = true;
localStorage.setItem(KEY_MP_PAUSED, '0');
iPos = setInterval(updateCurrentPosition, 1000);
});
player.addEventListener('pause', e => {
playing = false;
localStorage.setItem(KEY_MP_PAUSED, '1');
clearInterval(iPos);
});
toggle.addEventListener('click', e => {
e.preventDefault();
e.stopPropagation();
document.removeEventListener('click', userClick);
if (playing) {
player.pause();
toggle.classList.remove('music-on');
} else {
enablePlay();
}
});
})();
</script>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question