Javascript 如何在javascript中捕获浏览器的后退/前进按钮单击事件或哈希更改事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8208627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:07:51  来源:igfitidea点击:

How to capture browser's back/forward button click event or hash change event in javascript?

javascriptbrowserbackforward

提问by Student

I want to alert()when browser's back or forward button is clicked or hash is changed in javascript. I have tried thissolution and it is working but it is causing problems on other links in webpage and submit each request twice on any link click event.

我想当alert()浏览器的后退或前进按钮被点击或散列在 javascript 中更改时。我已经尝试过这个解决方案并且它正在工作,但它会导致网页中的其他链接出现问题,并在任何链接点击事件上提交每个请求两次。

Is there any solution to capture it without using setInterval()function? So I need to capture hash changeor back/forwardbutton click event? I need a simple javascript code/function/property that should work in all modern browsers.

有什么解决方案可以在不使用setInterval()功能的情况下捕获它吗?所以我需要捕获哈希更改后退/前进按钮单击事件?我需要一个简单的 javascript 代码/函数/属性,它应该适用于所有现代浏览器。

Any solution ?

任何解决方案?

Thanks

谢谢

回答by Robert Koritnik

Not a good idea

不是个好主意

Can you rather explain the reasoning behind this? We've all been down this road of preventing backs/forwards and similar and mangling with browser functionality.

你能解释一下这背后的原因吗?我们一直在这条防止后退/前进以及类似和破坏浏览器功能的道路上。

It turns out though it's better to obey to browser and write your application in that way so these things become irrelevant. And it's also true that browsers are locking more and more things to client javascript apps so it's highly likely your app is going to fail after (few) browser upgrades.

事实证明,虽然最好服从浏览器并以这种方式编写您的应用程序,以便这些事情变得无关紧要。而且浏览器将越来越多的东西锁定到客户端 javascript 应用程序也是事实,因此在(很少)浏览器升级后,您的应用程序很可能会失败。

Go with HTML5

使用 HTML5

HTML5 History specmay be exactly what you're after. It's the way things should work and be done in regard to Ajax applications and browser0s back/forward functionality. I suggest you check it out. See a working demothat does this rather nicely.

HTML5 历史规范可能正是您所追求的。这是有关 Ajax 应用程序和浏览器的后退/前进功能的工作和完成方式。我建议你检查一下。查看一个工作演示,它做得很好。

回答by Damian

I believe this is the answer Robert Koritnik was looking for, I found it here: https://developers.google.com/tv/web/articles/location-hash-navigation

我相信这是 Robert Koritnik 正在寻找的答案,我在这里找到了它:https: //developers.google.com/tv/web/articles/location-hash-navigation

There is an event (window.onhashchange) that fires whenever the location hash has been updated or changed so all you have to do is set up an event handler using JavaScript to listen for this event and execute code based on the hash. This is basically how it is done:

有一个事件 (window.onhashchange) 会在位置哈希更新或更改时触发,因此您只需使用 JavaScript 设置一个事件处理程序来侦听此事件并根据哈希执行代码。这基本上是如何完成的:

function getLocationHash() {
  return window.location.hash.substring(1);
}
window.onhashchange = function(e) {
  switch(getLocationHash()) {
    case 'state1': 
      execute code block 1;
      break;
    case 'state2':
      execute code block 2;
      break;
    default: 
      code to be executed if different from case 1 and 2;
  }
}

I have it working on my site: http://www.designhandler.com

我有它在我的网站上工作:http: //www.designhandler.com

It is all dynamically changing content. No ajax yet but when I am finished it will be. I still use the window.location.hash to keep track of the site states. If you navigate through the site and then begin to use the back forward buttons to navigate once the site is in the history it will change the states dynamically like if the user was actually clicking through the nav, rather than needing to reload the page afterward.

这都是动态变化的内容。还没有 ajax,但当我完成时它会。我仍然使用 window.location.hash 来跟踪站点状态。如果您浏览网站,然后在网站进入历史记录后开始使用后退按钮进行导航,它将动态更改状态,就像用户实际点击导航一样,而不需要事后重新加载页面。

回答by thexebolud

It's this for hash or for redirection? What are you trying to do? This kind of action is usually highly intrusive.

这是用于散列还是用于重定向?你想做什么?这种行为通常具有很强的侵入性。

You may want to try "onbeforeunload" event for this javascript before leaving the page

在离开页面之前,您可能想为此javascript尝试“onbeforeunload”事件



Edited

已编辑

Actually, the link you provide is quite accurate.

实际上,您提供的链接非常准确。

var hash = location.hash;

setInterval(function()
{
   if (location.hash != hash)
   {
       hashUpdatedEvent(hash);
   }
}, 100);

function hashUpdatedEvent(hash)
{
     switch(...);
}

Your link duplicate action problem would be corrected if you change

如果您更改,您的链接重复操作问题将得到纠正

<a href="javascript:void(0)" onclick="someFuncion()">Go for it</a>

function someFuncion()
{
   doWhatever();
   location.hash = 'somethingwasdone';
}

function hashUpdatedEvent(hash)
{
     if(hash == 'somethingwasdone')
     {
         doWhatever();
     }
}

By just (update the hash and let the "event" handle the action) :

仅通过(更新哈希并让“事件”处理操作):

<a href="javascript:void(0)" onclick="someFuncion()">Go for it</a>

function someFuncion()
{
   location.hash = 'somethingwasdone';
}

function hashUpdatedEvent(hash)
{
     if(hash == 'somethingwasdone')
     {
         doWhatever();
     }
}

回答by Praveen Poonia

Javascript provide the event popstateto capture browser's back/forward button click event -

Javascript 提供事件popstate来捕获浏览器的后退/前进按钮点击事件 -

window.addEventListener("popstate", function(e) { 
  // if a back or forward button is clicked, do whatever, like alert or anything

  console.log('href => ', e.path[0].location.href);
  // href =>  https://testdomain.com/demos/material/admin-app/#!/app/dashboard

  console.log('hash => ', e.path[0].location.hash);
  //hash =>  #!/app/dashboard

  console.log('pathname => ', e.path[0].location.pathname);
  //pathname =>  /demos/material/admin-app/

});

Read more on popstate

阅读有关popstate 的更多信息