How to Detect Browser Back Button event - Cross Browser

后端 未结 16 2704
鱼传尺愫
鱼传尺愫 2020-11-21 23:09

How do you definitively detect whether or not the user has pressed the back button in the browser?

How do you enforce the use of an in-page back button inside a sin

16条回答
  •  隐瞒了意图╮
    2020-11-21 23:50

    Here's my take at it. The assumption is, when the URL changes but there has no click within the document detected, it's a browser back (yes, or forward). A users click is reset after 2 seconds to make this work on pages that load content via Ajax:

    (function(window, $) {
      var anyClick, consoleLog, debug, delay;
      delay = function(sec, func) {
        return setTimeout(func, sec * 1000);
      };
      debug = true;
      anyClick = false;
      consoleLog = function(type, message) {
        if (debug) {
          return console[type](message);
        }
      };
      $(window.document).click(function() {
        anyClick = true;
        consoleLog("info", "clicked");
        return delay(2, function() {
          consoleLog("info", "reset click state");
          return anyClick = false;
        });
      });
      return window.addEventListener("popstate", function(e) {
        if (anyClick !== true) {
          consoleLog("info", "Back clicked");
          return window.dataLayer.push({
            event: 'analyticsEvent',
            eventCategory: 'test',
            eventAction: 'test'
          });
        }
      });
    })(window, jQuery);
    

提交回复
热议问题