简体   繁体   中英

Close firefox tab from javascript

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();

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)

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();
            }

You can try this code. If it is Firefox browser.

 gBrowser.removeCurrentTab();

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)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM