監聽瀏覽器返回按鈕並實現 點擊返回關閉當前頁面的功能chrome
關閉當前頁面(只在ie中生效)瀏覽器
window.close()
window.close()只能關閉彈窗和window.open()打開的窗口spa
chrome,ff寫法code
window.opener = null
window.open("about:blank","_self","")
window.close()
about:blank打開一個空白頁面blog
瀏覽器的返回能夠用監聽事件window.addEventListener('popstate',function(){})來實現,具體代碼以下:事件
var tempHash = window.location.hash;
if(window.history && window.history.pushState){
window.addEventListener('popstate',function(){
var hasLocation = location.hash;
var hashSplit = hashLocation.split("#");
var hashName = hashSplit[1];
if(hashName != ''){
var hash = window.location.hash;
if(hash == tempHash){
window.opener = null
window.open("about:blank","_self","")
window.close()
}
}
});
window.history.replaceState('forward',null,window.location.hash + '#forward');
window.history.pushState('forward',null,tempHash);
tempHash = window.location.hash;
}
window.location.hash 經過識別#forward來肯定當前頁面,女友明天就要來了,好開心,不寫了
另外也能夠實現屏蔽瀏覽器的回退按鈕
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});