天天看點

vue禁用浏覽器傳回鍵

mounted () {

  // 禁用浏覽器傳回鍵
  history.pushState(null, null, document.URL);
  window.addEventListener('popstate', this.disableBrowserBack);

},

destroyed() {

  // 清除popstate事件 否則會影響到其他頁面
  window.removeEventListener("popstate", this.disableBrowserBack, false);

},

methods: {

  disableBrowserBack() {
    history.pushState(null, null, document.URL);
  }

}
           

history的認識

history 對象包含浏覽器曆史。

常見屬性/方法:

  • history.length - 屬性儲存着曆史記錄的 URL 數量;
  • history.back() - 等同于在浏覽器點選後退按鈕;
  • history.forward() - 等同于在浏覽器中點選前進按鈕;
  • history.go() - 加載 history 清單中的某個具體頁面。

 H5新增了屬性/方法/事件:

  • history.state - 屬性用來儲存記錄對象;
  • history.pushState() - 向浏覽器的曆史記錄中添加一個狀态;
  • history.replaceState() - 修改目前曆史記錄實體;
  • popstate事件 - 當活動曆史記錄條目更改時,将觸發

(1).history.state

傳回目前頁面的 state 對象

(2).history.pushState(state, title, url)

  state: 狀态對象可以是任何可以序列化的對象。

  title: 目前大多數浏覽器都忽略此參數,盡管将來可能會使用它。

  url: 新曆史記錄條目的 URL 由此參數指定。如果未指定此參數,則将其設定為文檔的目前 URL。

3.history.replaceState(state, title, url)

  修改目前曆史記錄實體,如果你想更新目前的 state 對象或者目前曆史實體的 URL 來響應使用者的的動作的話這個方法将會非常有用。參數與 pushState 類似。

4.popstate事件

  當活動曆史記錄條目更改時,将觸發 popstate 事件。

  需要注意的是調用 history.pushState() 或 history.replaceState() 不會觸發 popstate 事件。隻有在做出浏覽器動作時,才會觸發該事件,如使用者點選浏覽器的回退按鈕(或者在 Javascript 代碼中調用 history.back() 或者 history.forward() 方法)。

  不同的浏覽器在加載頁面時處理 popstate 事件的形式存在差異。頁面加載時 Chrome 和 Safari 通常會觸發(emit ) popstate 事件,但 Firefox 則不會

白日不到處,青春恰自來,苔花如米小,也學牡丹開。

标簽: 浏覽器回退鍵禁用, vue禁用浏覽器傳回鍵