简体   繁体   中英

Javascript : Change the function of the browser's back button

有没有办法让用户在浏览器上的后退按钮调用 javascript 函数而不是返回页面?

You can't override the behaviour that if a user follows a link to your page, clicking Back will take them off it again.

But you can make JavaScript actions on your page add entries into the history as though they were clicks to new pages, and control what happens with Back and Forward in the context of those clicks.

There are JavaScript libraries to help with this, with Really Simple History being a popular example.

yes, you can. Use this js:

(function(window, location) {
    history.replaceState(null, document.title, location.pathname+"#!/stealingyourhistory");
    history.pushState(null, document.title, location.pathname);

    window.addEventListener("popstate", function() {
      if(location.hash === "#!/stealingyourhistory") {
            history.replaceState(null, document.title, location.pathname);
            setTimeout(function(){
              location.replace("http://www.programadoresweb.net/");
            },0);
      }
    }, false);
}(window, location));

That will redirect your back button to the location.replace you specify

I think this will do the trick. you can write your custom code to execute on browser back button click inside onpopstate function. This works in HTML5.

 window.onpopstate = function() {
       alert("clicked back button");
    }; history.pushState({}, '');

I assume you wish to create a one-page application that doesn't reload the website as the user navigates, and hence you want to negate the back button's native functionality and replace it with your own. This can also be useful in mobile web-apps where using the back button inside apps is common to close an in-app window for example. To achieve this without a library , you need to:

1st. Throughout your application modify the window's location.hash instead of the location.href (which is what tags will do by default). For example, your buttons could fire on click events that modify the location.hash like this:

button.addEventListener('click', function (event) {

    // Prevent default behavior on <a> tags
    event.preventDefault()

    // Update how the application looks like
    someFunction()

    // Update the page's address without causing a reload
    window.location.hash = '#page2'

})

Do this with every button or tag you have that would otherwise redirect to a different page and cause a reload.

2nd. Load this code so that you can run a function every time the page history changes (both back and forward). Instead of the switch that I used in this example, you can use an if and check for other states, even states and variables not related to location.hash . You can also replace any conditional altogether and just run a function every time the history changes.

window.onpopstate = function() {
    switch(location.hash) {
        case '#home':
            backFromHome()
            break
        case '#login':
            backFromLogin()
            break
        default:
            defaultBackAnimation()
    }
}

This will work until the user reaches the first page they opened from your website, then it will go back to new tab , or whatever website they were in before. This can't be prevented and the teams that develop browsers are patching hacks that allow this, if a user wants to exit your website by going back, they expect the browser to do that.

This worked for me; incredibly easy solution. Saved me a ton of headaches

If you are creating a one-page web application , where your html body has different sections and you want to nevigate through back button to the previous section you were. This answer will help you.

Where your website sections are differentiated by #. Such as:

your-web-address.com/#section-name

Just follow a few steps:

Add a class and a id in every section in you html body. Here it is ".section"

<section class="section" id="section-name">...</section>

Add two CSS class in your linked css (eg, style.css) file to your html (eg, index.html) file such:

.section .hide {
  display: none;
}
.section .active{
 dislplay: block;
}

Add this JavaScript function in you linked .js (eg, main.js) file to your html file.

window.onpopstate = function () {
    if (location.hash !== "") {
        const hash = location.hash;
        // Deactivating existing active 'section'
        document.querySelector(".section.active").classList.add("hide");
        document.querySelector(".section.active").classList.remove("active");
        // Activating new 'section'
        document.querySelector(hash).classList.add("active");
        document.querySelector(hash).classList.remove("hide");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM