簡體   English   中英

JavaScript 或 jQuery 瀏覽器后退按鈕點擊檢測器

[英]JavaScript or jQuery browser back button click detector

有人可以分享經驗/代碼我們如何檢測瀏覽器后退按鈕點擊(對於任何類型的瀏覽器)?

我們需要滿足所有不支持 HTML5 的瀏覽器

'popstate' 事件僅在您之前推送某些內容時有效。 所以你必須做這樣的事情:

jQuery(document).ready(function($) {

  if (window.history && window.history.pushState) {

    window.history.pushState('forward', null, './#forward');

    $(window).on('popstate', function() {
      alert('Back button was pressed.');
    });

  }
});

對於瀏覽器向后兼容性,我推薦: history.js

在 javascript 中,導航類型 2 表示點擊瀏覽器的后退或前進按鈕,瀏覽器實際上是從緩存中獲取內容。

if(performance.navigation.type == 2) {
    //Do your code here
}

有很多方法可以檢測用戶是否單擊了“后退”按鈕。 但一切都取決於您的需求。 嘗試探索下面的鏈接,它們應該對您有所幫助。

檢測用戶是否在當前頁面按下了“返回”按鈕:

在上一頁(“前進”)按“后退”按鈕后檢測當前頁面是否被訪問:

發現它可以很好地跨瀏覽器和移動back_button_override.js

(為 safari 5.0 添加了一個計時器)

// managage back button click (and backspace)
var count = 0; // needed for safari
window.onload = function () { 
    if (typeof history.pushState === "function") { 
        history.pushState("back", null, null);          
        window.onpopstate = function () { 
            history.pushState('back', null, null);              
            if(count == 1){window.location = 'your url';}
         }; 
     }
 }  
setTimeout(function(){count = 1;},200);

在 HTML5 的情況下,這將解決問題

window.onpopstate = function() {
   alert("clicked back button");
}; history.pushState({}, '');

你可以使用這個很棒的插件

https://github.com/ianrogren/jquery-backDetect

您需要做的就是編寫此代碼

  $(window).load(function(){
    $('body').backDetect(function(){
      // Callback function
      alert("Look forward to the future, not the past!");
    });
  });

最好的

就我而言,我使用 jQuery .load()來更新 SPA (單頁 [web] 應用程序)中的DIV。

$(window).on('hashchange', ..)開始使用$(window).on('hashchange', ..)事件偵聽器,這個被證明具有挑戰性並且需要一些破解。 由於閱讀了大量答案並嘗試了不同的變體,最終想出了如何使其以以下方式工作。 據我所知,到目前為止它看起來很穩定。

總之 - 每次加載視圖時都應該設置變量globalCurrentHash

然后當$(window).on('hashchange', ..)事件偵聽器運行時,它會檢查以下內容:

  • 如果location.hash具有相同的值,則表示前進
  • 如果location.hash具有不同的值,則表示返回

我意識到使用全局變量並不是最優雅的解決方案,但到目前為止,在 JS 中做面向對象的事情對我來說似乎很棘手。 改進/改進的建議當然值得贊賞


設置:

  1. 定義一個全局變量:
    var globalCurrentHash = null;
  1. 當調用.load()更新 DIV 時,也要更新全局變量:

     function loadMenuSelection(hrefVal) { $('#layout_main').load(nextView); globalCurrentHash = hrefVal; }
  2. 在頁面准備好后,設置偵聽器以檢查全局變量以查看是否按下了后退按鈕:

     $(document).ready(function(){ $(window).on('hashchange', function(){ console.log( 'location.hash: ' + location.hash ); console.log( 'globalCurrentHash: ' + globalCurrentHash ); if (location.hash == globalCurrentHash) { console.log( 'Going fwd' ); } else { console.log( 'Going Back' ); loadMenuSelection(location.hash); } }); });

它在 HTML5 History API 中可用。 該事件稱為'popstate'

通過以下功能禁用 url 按鈕

window.onload = function () {
    if (typeof history.pushState === "function") {
        history.pushState("jibberish", null, null);
        window.onpopstate = function () {
            history.pushState('newjibberish', null, null);
            // Handle the back (or forward) buttons here
            // Will NOT handle refresh, use onbeforeunload for this.
        };
    }
    else {
        var ignoreHashChange = true;
        window.onhashchange = function () {
            if (!ignoreHashChange) {
                ignoreHashChange = true;
                window.location.hash = Math.random();
                // Detect and redirect change here
                // Works in older FF and IE9
                // * it does mess with your hash symbol (anchor?) pound sign
                // delimiter on the end of the URL
            }
            else {
                ignoreHashChange = false;
            }
        };
    }
};

Hasan Badshah回答對我有用,但該方法將被棄用,並且可能對其他人造成問題。 遵循有關替代方法的 MDN 網絡文檔,我在這里登陸: PerformanceNavigationTiming.type

if (performance.getEntriesByType("navigation")[0].type === 'back_forward') {
  // back or forward button functionality
}

這並不能直接解決前進按鈕上的后退按鈕,但足以滿足我的需要。 在文檔中,他們詳細說明了可能有助於解決您的特定需求的可用事件數據:

function print_nav_timing_data() {
  // Use getEntriesByType() to just get the "navigation" events
  var perfEntries = performance.getEntriesByType("navigation");

  for (var i=0; i < perfEntries.length; i++) {
    console.log("= Navigation entry[" + i + "]");
    var p = perfEntries[i];
    // dom Properties
    console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - 
    p.domContentLoadedEventStart));
    console.log("DOM complete = " + p.domComplete);
    console.log("DOM interactive = " + p.interactive);

    // document load and unload time
    console.log("document load = " + (p.loadEventEnd - p.loadEventStart));
    console.log("document unload = " + (p.unloadEventEnd - 
    p.unloadEventStart));

    // other properties
    console.log("type = " + p.type);
    console.log("redirectCount = " + p.redirectCount);
  }
}

根據本文發布時的文檔,它仍處於工作草案狀態,IE 或 Safari 不支持,但在完成時可能會發生變化。 檢查文檔以獲取更新。

假設你有一個按鈕:

<button onclick="backBtn();">Back...</button>

這里是 backBtn 方法的代碼:

  function backBtn(){
                    parent.history.back();
                    return false;
                }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM