This question is brought up because of this. The problem is, probably, the page is designed to generate a confirmation alert only if the user click on browser X button. I know that window.close() will close the current browser window which probably is not the same as clicking the X of browser window. Is there any way, possibly with JavaScript to recreate the click action on browser X button as if a real user would do?
1 Answer
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()
So, there is not a way to close browser via javascript, but if you wan't to tigger some code that is supposed to be executed when window closes try this:
//plain js
window.onunload();
//plain js
window.onbeforeunload();
//jQuery
$(window).unload();
Or if you want to execute code when user tries to close window, try this:
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
These events are fired in this order:
- window.beforeunload (cancellable event)
- window.pagehide
- window.unload
1 Comment
window.open() or at least something similar. Because window.close() closed the browser. But, If I perform click on X there is another pop up shows up to confirm the action which I do not get using selenium. I want to recreate the same with some kind of programming
window.close()will only work in child windows/tabs. You cannot close the parent browser window.window.close()?