Search code examples
javascripthttp-redirectbrowser-historybackpopstate

Good-willed Back Button Redirect Script?


I am trying to put the Back Button Redirect Script function to good use. I have a plugin which plays background (user-initiated) music on my site. As long as the user clicks forward, the music streams continuously and nearly uninterrupted from page to page, without restarting. If the user clicks the back button (or refreshes), the music stops and they must manually press play to restart the stream. The author says they have no way to resolve it. I'm not giving up just yet.

My thought is, why not use JavaScript to record the browser's previous page URL, then capture the back button trigger and send the user "forward" to that URL, thus keeping the music stream intact while honoring the user's desire to go back a page?

Conceptually, being a supernoob at JavaScript, I patched this together from different sources on here and codingbeautydev...

$(window).bind("onpopstate", function (e) {
    const previousPage = document.getElementById("previous-page");
    previousPage.textContent = document.referrer;

    window.history.pushState({ page: 1 }, "", "");
    window.onpopstate = function (event) {
        if (event) {
            window.location.href = previousPage;
        }
    };
});

My first thought is there are surely some syntex errors in there at my doing and potentially much more that need be modified, but I'm hoping someone can easily touch up my rough sketch. Additionally, beyond making this work, I see the limits of this allowing only 1-page of history, and I'm curious if there's a way to nest it into a stack of a few pages to which could be visited in reverse order, all the while moving "forward". First things first though, then on to bigger and better.

Thanks guys! 😀 Mark


Solution

  • You cannot change the default behavior of the browsers's back or forward button unless your app uses URL hashes to navigate, but from my understanding of your question the user actually goes from say .com/paper to .com/boxes and not .com/paper#page1 to .com/paper#page2.

    One possible option you could try is using the following (from here):

    window.addEventListener('pageshow', function (event) {
        if (event.persisted || performance.getEntriesByType("navigation")[0].type === 'back_forward') {
            // User got here from using the Back or Forward button
        }
    });
    

    This will trigger when the user got on the page this code runs on using the back or forward window button, also if the user goes from /boxes back to /paper.

    You can try to save the current state of the music playing on the background (which song, timestamp, audio level, etc) in local storage (at max) every second or so, and get the stored values inside the function above to continue the music the user was last listening to when he left the previous page. Not the most elegant solution, but all I think of right now that might actually work.

    Edit:

    The code you requested. Chrome & Safari will block/ignore it due to history manipulation, except when an user interacts with the page first. It's not how history should be used. Don't use it in production, but play with it all you want. Also, here's an simple example how history can be used.

    window.history.pushState({}, '', window.location.pathname);
    let previousPage = document.referrer;
    window.addEventListener('popstate', (e) => {    
        window.location.assign(previousPage)
    });