在應用中,經常看見支付成功之後,會有倒計時關閉網頁。去年我寫過一個關閉網頁的小demo
- HTML
- JS
function task(){
var n=$('.autoClose').html()[];
if(n>){//如果n>1
n--;//n-1
$('.autoClose').html($('.autoClose').html().replace(/^\d/,n));
}else{//否則
window.close();
}
}
}
//将task放入周期性定時器,時間間隔為1000
var timer=setInterval(task,);
當時寫的時候是好使的,現在在本地也是好使的。。。可是一到伺服器就不行了,出現下圖的問題

Scripts may close only the windows that were opened by it.
查了下資料,說是在新版的浏覽器中不支援此方法了。詳細解釋看本篇文章,我寫下我的解決辦法,在不支援
window.close()
的頁面,将他變為空白頁。改過之後是這樣的:
function task(){
var n=$('.autoClose').html()[];
if(n>){//如果n>1
n--;//n-1
$('.autoClose').html($('.autoClose').html().replace(/^\d/,n));
}else{//否則
var userAgent = navigator.userAgent;
if (userAgent.indexOf("Firefox") != - || userAgent.indexOf("Chrome") !=-) {
window.location.href="about:blank";
} else {
window.opener = null;
window.open("", "_self");
window.close();
}
}
}
//将task放入周期性定時器,時間間隔為1000
var timer=setInterval(task,);