简体   繁体   English

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

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

I want to alert() when browser's back or forward button is clicked or hash is changed in javascript. 我想在点击浏览器的后退或前进按钮或在javascript中更改散列时alert() I have tried this solution and it is working but it is causing problems on other links in webpage and submit each request twice on any link click event. 我已经尝试过这个解决方案并且它正在工作,但它会导致网页中的其他链接出现问题,并在任何链接点击事件上提交两次请求。

Is there any solution to capture it without using setInterval() function? 有没有使用setInterval()函数捕获它的解决方案? So I need to capture hash change or back/forward button click event? 所以我需要捕获哈希更改后退/前进按钮单击事件? I need a simple javascript code/function/property that should work in all modern browsers. 我需要一个简单的javascript代码/函数/属性,它应该适用于所有现代浏览器。

Any solution ? 有解决方案吗

Thanks 谢谢

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 spec may be exactly what you're after. HTML5历史规范可能正是您所追求的。 It's the way things should work and be done in regard to Ajax applications and browser0s back/forward functionality. 这是关于Ajax应用程序和browser0s后退/转发功能应该工作和完成的方式。 I suggest you check it out. 我建议你看看。 See a working demo that does this rather nicely. 看一个相当不错的工作演示

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. 每当更新或更改位置哈希时都会触发一个事件(window.onhashchange),因此您只需要使用JavaScript设置事件处理程序来侦听此事件并根据哈希执行代码。 This is basically how it is done: 这基本上就是这样做的:

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. 还没有ajax但是当我完成它将会是。 I still use the window.location.hash to keep track of the site states. 我仍然使用window.location.hash来跟踪站点状态。 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. 如果您浏览网站,然后在网站进入历史记录后开始使用后退按钮进行导航,则会动态更改状态,就像用户实际点击导航一样,而不是之后需要重新加载页面。

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 您可能希望在离开页面之前尝试此onjavascript的“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) : 通过just(更新哈希并让“event”处理动作):

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

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

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

Javascript provide the event popstate to 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的信息

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

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