How to detect if the user clicked the “back” button

后端 未结 5 603
说谎
说谎 2020-11-29 06:41

When the user goes history-back-1...how do I detect that? And then, alert \"the user clicked back!\"

Using binds (and jQuery preferably)

相关标签:
5条回答
  • 2020-11-29 07:11

    On the page you are looking at, you can add this piece of code to the onLoad event to move them back the page they were on.

    if(history.length>0)history.go(+1)
    

    If you want the alert then make it

    if(history.length>0)alert("the user clicked back!")
    
    0 讨论(0)
  • 2020-11-29 07:17

    try:

    window.onbeforeunload = function (evt) {
      var message = 'Are you sure you want to leave?';
      if (typeof evt == 'undefined') {
        evt = window.event;
      }
      if (evt) {
        evt.returnValue = message;
      }
      return message;
    }
    
    0 讨论(0)
  • 2020-11-29 07:22
    window.onpopstate=function()
    {
      alert("Back/Forward clicked!");
    }
    
    0 讨论(0)
  • 2020-11-29 07:29

    You generally can't (browser security restriction). You can tell if the user navigates away from the page (onbeforeunload, onunload fire) but you can't tell where they went unless you've set up your page to allow it.

    HTML5 introduces the HTML5 History API; in conforming browsers, the onpopstate event will fire if the user navigates back to an earlier "page" on your site.

    0 讨论(0)
  • 2020-11-29 07:29

    Following are the steps to detect back button click

    1. Register a mouse down event on body $('body').on('mousedown' ,'on all li' );

      2.Now set a variable when mousedown event occur.

      3.Check this variable when your location changes.

    IF variable chages to true it means list cliked otherwise backbutton

    This work in my usecase .This solution may helps others because it depends on app design

    0 讨论(0)
提交回复
热议问题