Reputation: 49
I want to close Firefox tab from JavaScript. Please do not misunderstand me. I am not trying to close popup window but tab. I know JavaScript cannot close the window which it has not opened. Therefore I tried below code but it works in all browsers but not in Firefox.
window.open('','_self','');
Window.close();
Upvotes: 4
Views: 18717
Reputation: 21
According to Mozilla Firefox Deverlopers forum, it is not possible now. Read below.
"In the past, when you called the window object's close() method directly, rather than calling close() on a window instance, the browser closed the frontmost window, whether your script created that window or not. This is no longer the case; for security reasons, scripts are no longer allowed to close windows they didn't open. (Firefox 46.0.1: scripts can not close windows, they had not opened)"
Upvotes: 2
Reputation: 31
You can try this code. If it is Firefox browser.
gBrowser.removeCurrentTab();
Upvotes: 3
Reputation: 3201
If you have a single/few-user page and you have access to the Firefoxes you can change the about:config
settings.
dom.allow_scripts_to_close_windows = true
This might be a big security issue!
(Tested with Firefox 27 on Linux)
Upvotes: 6
Reputation: 7746
Here is something I learnt from a StackOverflow thread (unfortunately could not find it to link to this answer):
window.open(document.URL,'_self','resizable=no,top=-245,width=250,height=250,scrollbars=no');
window.close();
This closes the window/tab. It can be characterized as a hack. Essentially, it fools the browser into thinking that the current window is a window/tab opened by JavaScript. Because the rule appears to be that JavaScript can close a window that was opened by JavaScript.
It works in Chrome, Firefox. Internet Explorer needs a little extra treatment to account for varying behavior since IE 6 to IE 8+. I am including that too, if anyone's interested.
var Browser = navigator.appName;
var indexB = Browser.indexOf('Explorer');
if (indexB > 0) {
var indexV = navigator.userAgent.indexOf('MSIE') + 5;
var Version = navigator.userAgent.substring(indexV, indexV + 1);
if (Version >= 7) {
window.open('', '_self', '');
window.close();
}
else if (Version == 6) {
window.opener = null;
window.close();
}
else {
window.opener = '';
window.close();
}
}
else {
window.close();
}
Upvotes: 3