简体   繁体   English

Javascript : 改变浏览器后退按钮的功能

[英]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.但是您可以在您的页面上进行 JavaScript 操作,将条目添加到历史记录中,就好像它们是对新页面的点击一样,并控制在这些点击的上下文中使用 Back 和 Forward 发生的情况。

There are JavaScript libraries to help with this, with Really Simple History being a popular example.有 JavaScript 库可以帮助解决这个问题, Really Simple History是一个流行的例子。

yes, you can.是的你可以。 Use this js:使用这个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这会将您的后退按钮重定向到您指定的 location.replace

I think this will do the trick.我认为这会成功。 you can write your custom code to execute on browser back button click inside onpopstate function.您可以编写自定义代码以在onpopstate函数内单击浏览器后退按钮时执行。 This works in HTML5.这适用于 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).在整个应用程序中修改窗口的location.hash而不是location.href (这是标签默认执行的操作)。 For example, your buttons could fire on click events that modify the location.hash like this:例如,您的按钮可以触发修改location.hash的点击事件,如下所示:

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 .除了我在本例中使用的开关,您可以使用 if 并检查其他状态,甚至是与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.如果您正在创建一个单页 Web 应用程序,其中您的 html 正文有不同的部分,并且您希望通过后退按钮导航到您所在的上一个部分。 This answer will help you.这个答案会对你有所帮助。

Where your website sections are differentiated by #.您的网站部分以 # 区分的位置。 Such as:如:

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

Just follow a few steps:只需执行几个步骤:

Add a class and a id in every section in you html body.在 html 正文的每个部分中添加一个类和一个 id。 Here it is ".section"这里是“.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:在链接的 css(例如 style.css)文件中添加两个 CSS 类到您的 html(例如 index.html)文件中,例如:

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

Add this JavaScript function in you linked .js (eg, main.js) file to your html file.将此 JavaScript 函数添加到您链接的 .js(例如 main.js)文件到您的 html 文件中。

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");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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