禁用回退&開啟回退
// 必須聲明方法 否則無法刪除此監聽器 function backCommon() { history.pushState(null, null, document.URL); } // 禁用瀏覽器回退頁面操作 history.pushState(null, null, document.URL); window.addEventListener('popstate', backCommon); // 開啟瀏覽器回退頁面操作 window.removeEventListener('popstate', backCommon); window.location.href = "/word/show";
禁用回退&無法開啟回退
// 如果你希望用戶不用有返回功能 可縮寫如下 或使用location.replace('url')跳轉鏈接 history.pushState(null, null, document.URL); window.addEventListener('popstate', function () { history.pushState(null, null, document.URL); });
url常用方法
// 獲取整個url或跳轉url window.location.href; // 設置或獲取url問號后參數 window.location.search; // 設置或獲取href屬性中在井號后的值 window.location.hash; // 設置或獲取url的協議 window.location.protocol; // 設置或獲取url的hostname localhost/user?id=1返回'/user' window.location.hostname; // 設置或獲取url端口號 window.location.port;
js常用返回方法
// 返回上頁 history.go(-1); // 返回上上頁 history.go(-2); // 返回上頁 有人說back返回會刷新上個頁面但我的操作過程中頁面並沒有刷新 history.back(); // 返回上頁 history.back(-1); // 返回下一頁 history.go(1); // 返回下一頁 history.forward(); // 產生點擊前進按鈕的效果 抵消用戶點擊后退按鈕所產生事件 istory.forward(1);
刷新頁面
history.go(0); location.reload(); location = location; // 加載新頁面可以url可以前進后退 location.href = location.href; // 加載新頁面可以url可以前進后退 等同如上操作 location.assign(location); // 替換當前頁 清除url歷史記錄 無法前進后退 location.replace('http://www.baidu.com') // 此方法可以使當前頁面失去前進后退功能 location.replace(this.href); location.replace(location); document.execCommand('Refresh'); window.navigate(location); document.URL = location.href;
js獲取url中的參數
function geUrltParam(paramKay) { let reg = new RegExp("(^|&)" + paramKay + "=([^&]*)(&|$)", "i"); let r = location.search.substr(1).match(reg); return r == null ? null : decodeURI(r[2]); } // localhost:8080/index?openId=xxxx var openId = getQueryString("openId");