这个问题是因为this而提出的.问题可能是,该页面设计为仅当用户单击浏览器 X 按钮时才生成确认警报。我知道 window.close()
将关闭当前浏览器窗口,可能 与单击浏览器窗口的 X 不同。有没有什么方法可以使用 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 关闭浏览器,但是如果你不想触发一些应该在窗口关闭时执行的代码,试试这个:
//plain js
window.onunload();
//plain js
window.onbeforeunload();
//jQuery
$(window).unload();
或者如果你想在用户试图关闭窗口时执行代码,试试这个:
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
关于javascript - 使用 JavaScript 调用浏览器 X 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29055221/