使用 JavaScript 调用浏览器 X 按钮
Invoke browser X button with JavaScript
提出这个问题是因为。问题可能是,该页面设计为仅当用户单击浏览器 X 按钮时才生成确认警报。我知道window.close()
会关闭当前浏览器window这可能和点击浏览器X不一样window。有没有什么办法,可能用 JavaScript 在浏览器 X 按钮上重新创建点击操作,就好像真实用户会做的那样?
window.close()
This method is only allowed to be called for windows that were opened
by a script using the window.open() method. If the window was not
opened by a script, the following error appears in the JavaScript
Console: Scripts may not close windows that were not opened by script. Mozilla Developer Network: window.close()
所以,没有办法通过 javascript 关闭浏览器,但是如果你不想触发一些应该在 window 关闭时执行的代码,试试这个:
//plain js
window.onunload();
//plain js
window.onbeforeunload();
//jQuery
$(window).unload();
或者如果您想在用户尝试关闭时执行代码 window,试试这个:
window.onbeforeunload = function(){
// Do something
}
// OR
window.addEventListener("beforeunload", function(e){
// Do something
}, false);
window.onunload = function(){
// Do something
}
// OR
window.addEventListener("unload", function(e){
// Do something
}, false);
// jQuery
$(window).unload(function(){
// Do whatever you need
});
Since 25 May 2011, the HTML5 specification states that calls to
window.alert(), window.confirm(), and window.prompt() methods may be
ignored during this event. See the HTML5 specification for more
details. MDN | window.onbeforeunload
这些事件按以下顺序触发:
- window.beforeunload(可取消事件)
- window.pagehide
- window.unload
提出这个问题是因为window.close()
会关闭当前浏览器window这可能和点击浏览器X不一样window。有没有什么办法,可能用 JavaScript 在浏览器 X 按钮上重新创建点击操作,就好像真实用户会做的那样?
window.close()
This method is only allowed to be called for windows that were opened by a script using the window.open() method. If the window was not opened by a script, the following error appears in the JavaScript Console: Scripts may not close windows that were not opened by script. Mozilla Developer Network: window.close()
所以,没有办法通过 javascript 关闭浏览器,但是如果你不想触发一些应该在 window 关闭时执行的代码,试试这个:
//plain js
window.onunload();
//plain js
window.onbeforeunload();
//jQuery
$(window).unload();
或者如果您想在用户尝试关闭时执行代码 window,试试这个:
window.onbeforeunload = function(){
// Do something
}
// OR
window.addEventListener("beforeunload", function(e){
// Do something
}, false);
window.onunload = function(){
// Do something
}
// OR
window.addEventListener("unload", function(e){
// Do something
}, false);
// jQuery
$(window).unload(function(){
// Do whatever you need
});
Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML5 specification for more details. MDN | window.onbeforeunload
这些事件按以下顺序触发:
- window.beforeunload(可取消事件)
- window.pagehide
- window.unload