window.close and self.close do not close the window in Chrome

669,256

Solution 1

Ordinary javascript cannot close windows willy-nilly. This is a security feature, introduced a while ago, to stop various malicious exploits and annoyances.

From the latest working spec for window.close():

The close() method on Window objects should, if all the following conditions are met, close the browsing context A:

  • The corresponding browsing context A is script-closable.
  • The browsing context of the incumbent script is familiar with the browsing context A.
  • The browsing context of the incumbent script is allowed to navigate the browsing context A.

A browsing context is script-closable if it is an auxiliary browsing context that was created by a script (as opposed to by an action of the user), or if it is a browsing context whose session history contains only one Document.

This means, with one small exception, javascript must not be allowed to close a window that was not opened by that same javascript.

Chrome allows that exception -- which it doesn't apply to userscripts -- however Firefox does not. The Firefox implementation flat out states:

This method is only allowed to be called for windows that were opened by a script using the window.open method.


If you try to use window.close from a Greasemonkey / Tampermonkey / userscript you will get:
Firefox: The error message, "Scripts may not close windows that were not opened by script."
Chrome: just silently fails.



The long-term solution:

The best way to deal with this is to make a Chrome extension and/or Firefox add-on instead. These can reliably close the current window.

However, since the security risks, posed by window.close, are much less for a Greasemonkey/Tampermonkey script; Greasemonkey and Tampermonkey could reasonably provide this functionality in their API (essentially packaging the extension work for you).
Consider making a feature request.



The hacky workarounds:

Chrome is currently was vulnerable to the "self redirection" exploit. So code like this used to work in general:

open(location, '_self').close();

This is buggy behavior, IMO, and is now (as of roughly April 2015) mostly blocked. It will still work from injected code only if the tab is freshly opened and has no pages in the browsing history. So it's only useful in a very small set of circumstances.

However, a variation still works on Chrome (v43 & v44) plus Tampermonkey (v3.11 or later). Use an explicit @grant and plain window.close(). EG:

// ==UserScript==
// @name        window.close demo
// @include     http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant       GM_addStyle
// ==/UserScript==

setTimeout (window.close, 5000);

Thanks to zanetu for the update. Note that this will not work if there is only one tab open. It only closes additional tabs.


Firefox is secure against that exploit. So, the only javascript way is to cripple the security settings, one browser at a time.

You can open up about:config and set
allow_scripts_to_close_windows to true.

If your script is for personal use, go ahead and do that. If you ask anyone else to turn that setting on, they would be smart, and justified, to decline with prejudice.

There currently is no equivalent setting for Chrome.

Solution 2

Chrome Fixed the security issues on version 36.0.1985.125

Chrome 36.0.1985.125 WEDNESDAY, JULY 16, 2014 Release note

From my observation, this update fixed the issue on using window.close() to close the popup window. You will see this in the console when it fail, "Scripts may close only the windows that were opened by it.". That means The hacky workarounds (Brock Adams's answer) may not work in the latest release.

So, in the previous Chrome released builds, the below code block may worked but not with this update.

window.open('', '_self', '');
window.close();

For this update, you have to update your code accordingly to close the popup window. One of the solution is to grab the popup window id and use

chrome.windows.remove(integer windowId, function callback)

method to remove it. Chrome extension windows API can be found at chrome.windows.

Actually my chrome extension MarkView was facing this issue and I had to update my code to make it work for this Chrome Update. By the way, MarkView is tool to read and write Awesome Markdown Files, it provides features including Content Outline, Sortable Tables and code block syntax highlight with line number.

I also created this post, any comments are welcome.

Solution 3

In tampermonkey now you can use

// @grant        window.close

And then just simply call

window.close();

Solution 4

Requrements for this to work:

You have to open the window/tab from a window launcher to get a javascript handle to have it work, as it does not always work on a tab that was not opened via a window-launcher script. This test page shows you how:

http://browserstrangeness.bitbucket.io/window_close_tester.htm

If you don't see it working from my launcher, posting your browser, your device and versions are necessary. Browsers of different versions act differently on different devices. (Such as Firefox and Chrome on iPads which are NOT what they say they are. They are Safari with a different skin!)

So it is important to say for example 'I am using Safari 10.14 on an iPad using iOs 14.5' so I (or some other helpful individual here at stackoverflow) can research it for you and post results to help other users. Thanks in advance for doing that. If you use the launcher and it works on my example for you, then it works.

I am using the method posted by Brock Adams and it even works in Firefox, if it's user initiated by being launched by button or link from another window.

open(location, '_self').close();

I am calling it from a button press so it is user initiated, and it is still working fine using Chrome 90, Internet Explorer 11, Edge, Safari 7-10 and ALSO Firefox 35 & 88. I tested using version 8.1 & 10 of Windows and Mac OS X 10.6, 10.9 & 10.10 & 10.14 if that is different.


Self-Closing Window Code (on the page that closes itself)

The complete code to be used on the user-opened window that can close itself:

window_to_close.htm

JavaScript:

function quitBox(cmd)
{   
    if (cmd=='quit')
    {
        open(location, '_self').close();
    }   
    return false;   
}

HTML:

<input type="button" name="Quit" id="Quit" value="Quit" onclick="return quitBox('quit');" />

Here is that test page again with a working example: (Now tested in Chrome 90.0 and Firefox 88.0 -- both on Windows 10 and Mac 10.14 Mojave)

http://browserstrangeness.bitbucket.io/window_close_tester.htm


Window Opener Code (on a page that opens the above page)

To make this work, security-imposed cross browser compatibility requires that the window that is to be closed must have already been opened by the user clicking a button within the same site domain.

For example, the window that uses the method above to close itself, can be opened from a page using this code (code provided from my example page linked above):

window_close_tester.htm

JavaScript:

function open_a_window() 
{
    window.open("window_to_close.htm"); 

    return false;
}

HTML:

<input type="button" onclick="return open_a_window();" value="Open New Window/Tab" />

Solution 5

Many people are still trying to find a way to close the Chrome browser using javascript. The following method only works when you use Chrome as APP launcher - kiosk for example!

I have tested the following:

I'm using the following extension: Close Kiosk

I'm following the usage instructions and it seems to work just fine (make sure you clear the cache while doing the tests). The javascript I use is (attached to click event):

window.location.href = '/closekiosk';

I hope that helps somebody, as it's the only working solution I have found.

Note: It seems the extension runs in background and adds a Chrome tray icon. It has the following option checked: "Let Chrome run in background" (or similar text). You may need to play with it, until it work for you. I unchecked it and now it works just fine!

Share:
669,256

Related videos on Youtube

GµårÐïåñ
Author by

GµårÐïåñ

Read Mini Bio #SOreadytohelp

Updated on August 14, 2021

Comments

  • GµårÐïåñ
    GµårÐïåñ almost 3 years

    The issue is that when I invoke window.close() or self.close() it doesn't close the window. Now there seems to be a belief that in Chrome you can't close by script any window that is not script created. That is patently false but regardless it is supposed to still do it, even if it requires to pop up an alert to confirm. These are not happening.

    So does anyone have real, functional and proven method of closing a window using something like javascript:window.close() or javascript:self.close() that actually does what is expected and something that happens just fine in every browser that is NOT Chrome based? Any suggestions would be greatly appreciated and I am looking for Javascript specific solution, nothing JQuery or third party implementation.

    Update: While much of what has been suggested has serious limitations and usability issues, the latest suggestion (specific to TamperMonkey) using // @grant window.close in the script header will often do the trick even on those tabs that normally can't handle the close method. While not entirely ideal and doesn't generalized to every case, it is a good solution in my case.

    • mash
      mash over 10 years
      window.close() works for me in chrome.
    • Blender
      Blender over 10 years
      window.close is not part of any standard, so there's no guarantee of consistency (or even implementation) across browsers.
    • Blender
      Blender over 10 years
      @GµårÐïåñ: Umm, no it isn't. It has nothing to do with the language. It's a function implemented by browsers. If you can write a minimal example showing how window.close isn't working the way it should, I think that may be more helpful than saying, "it doesn't work".
    • GµårÐïåñ
      GµårÐïåñ over 10 years
      I gave you TWO examples. Spelling it out for you, <a href="javascript:window.close">CLOSE</a>
    • George
      George over 9 years
      guardian that is improper javascript. Try window.close() and it works. window.close is just a variable name and will not call the function (at least it does not when I test it in chrome 37). When I change your example to window.close() it works in chrome 37.
    • GµårÐïåñ
      GµårÐïåñ over 9 years
      @George what you have said is moot and adds nothing.
    • Superole
      Superole over 9 years
      GµårÐïåñ What @George said is NOT moot (unless I've totally misunderstood the meaning of the word). He is correct in stating that you have a syntactic error in the javascript in your examples, and if you have the same error in your application-code, then this is more than likely the cause of your issue. IF, however, these are just typos in your examples, then you should correct those typos to get better answers.
  • GµårÐïåñ
    GµårÐïåñ over 10 years
    Hey my friend, glad to finally hear from you. Just a note, on Fx you can bypass that limitation by flipping the dom.allow_scripts_to_close_windows;false to true but I guess nothing in Chrome without hacking the source/rebuild which is how I got around it for now. I know and have talked to the TM developer and in the recent alpha/beta we have put it as a compatibility option (setting of the script) to run in man-in-the-middle style, works. I guess short of the hacks we have no clean solution, pity.
  • Bron Davies
    Bron Davies about 10 years
    If anyone is having trouble with window.close or the particular behavior difference among browsers, read this answer very carefully - it really does have all the right information.
  • Brock Adams
    Brock Adams about 10 years
    Forgot about the user initiated exceptions; good catch. I think most userscripters want fully automatic operation though. They already have a handy, user initiated close mechanism -- that little X in the upper right. (^_^)
  • Jscti
    Jscti almost 10 years
    Is there a way to check if the window was opened by script or not ? (I need to show/hide a back button, I don't want to use the hack) Thanks EDIT: window.opener === null
  • swcool
    swcool almost 10 years
    Since Chrome 36.0.1985.125 WEDNESDAY, JULY 16, 2014, The hacky workarounds may not work, detail in my answer.
  • Brock Adams
    Brock Adams almost 10 years
    The correct hack is open(location, '_self').close(); -- note the use of the return value from open(). This still works on Chrome 36.0.1985.125 m
  • Brock Adams
    Brock Adams almost 10 years
    @swcool, just retested on Chrome 36.0.1985.125 m. The hack still works; but it's reasonable to assume it will be blocked sometime in the future.
  • swcool
    swcool almost 10 years
    @brock-adams, interesting. For my extension project, I have to make change for this Chrome new update, otherwise it won't work any more. Thanks for your reply.
  • swcool
    swcool almost 10 years
    In my case, I just test again with open(location, '_self').close();, I got "Unauthorized" error on this. This error is different with 'window.close()(warning on this"Scripts may close only the windows that were opened by it."). It looked like open(location, '_self').close();` moved forward a little bit, but it can't complete in my case. Thanks @brock-adams for the comment.
  • DevT
    DevT almost 10 years
    I have typescript and when i put chrome.windows.remove it says could not find symbol chrome. how can i resolve this? do i need to add some sort of reference?
  • swcool
    swcool almost 10 years
    @devt chrome.windows.remove is Chrome extension API, your javascript should be recognized by your chrome extension program. You can try it inside background.js, in your chrome extension manifest.json you need to have: "background": { "scripts": ["background.js"], ... },
  • LordOfThePigs
    LordOfThePigs over 9 years
    Somehow, this doesn't work for me. Neither on firefox 30 nor on Chrome 37. All it does is make the page become blank (really weird behavior). My code is <button onclick="open(location,'_self').close()" >Close Window</button>. Am I doing something obviously wrong? It seems to me that this is also user initiated. Note that I get the same result if I use a <button> or an <input type="button">.
  • Jeff Clayton
    Jeff Clayton over 9 years
    Added a test page above in the answer for you.
  • kad81
    kad81 over 9 years
    This also suffers from the "Scripts may not close windows that were not opened by script." problem mentioned in other answers.
  • m3nda
    m3nda about 9 years
    I use Firefox and i put both allow_scripts_to_close_windows;true and open(location, '_self').close(); to make it work. Thanks a lot.
  • Stephan
    Stephan almost 9 years
    Can you add your Chrome version please?
  • DfrDkn
    DfrDkn almost 9 years
    My chrome version is 43.0.2357.81.
  • alianos-
    alianos- almost 9 years
    For me that just replaces the current window, with a window at /location.
  • napstercake
    napstercake almost 9 years
    @alianos- for me too.
  • napstercake
    napstercake almost 9 years
    It is just replacing the curren window. No more.
  • shinzou
    shinzou over 8 years
    The hacky chrome solution doesn't work. Can I turn a tampermonkey script to an extension and this will give it the privilege to close a tab?
  • Brock Adams
    Brock Adams over 8 years
    @kuhaku, try injecting the workaround. I haven't retested on latest Chrome in a while, but swcool erroneously reported that the hole has been plugged. Yes, extensions can close just about any tab.
  • shinzou
    shinzou over 8 years
    By injecting it you mean like this? pastebin.com/XgRJu31a it doesn't work. It just keep refreshing the page endlessly.
  • Brock Adams
    Brock Adams over 8 years
    @kuhaku: No, use addJS_Node() from this answer.
  • shinzou
    shinzou over 8 years
    I either do something wrong or it doesn't work, I bet it's the first option: pastebin.com/8VmBkV6j
  • Brock Adams
    Brock Adams over 8 years
    @kuhaku: Yes, you still need to create a GM_main() function and put the location hack inside it. However, I just retested and this will now only work if the tab was freshly opened. That is the tab is still on its first page and has nothing in the tab's browsing history. If that is not your case, then your only recourse is to write an extension.
  • zanetu
    zanetu over 8 years
    window.close() will work in Tampermonkey if you set @grant to a value other than none. See this thread.
  • zanetu
    zanetu over 8 years
    @Brock Adams What do you mean by "navigation"? I tried a global userscript (i.e. hastebin.com/raw/uwexuyusen) containing setTimeout(window.close, 5000) and randomly scrolling and clicking links on a page (including links pointing to parts of the current page, and links pointing to another website) but it always works (in Chrome v44.0.2403.155 and Tampermokey BETA v3.12.4752). One restriction of Tampermonkey I forgot to mention is that you cannot close a tab using window.close() if that is the only one left, that is, you cannot shut down Chrome completely.
  • Brock Adams
    Brock Adams over 8 years
    You're right, @zanetu, your script works for me too on TM 3.11 and Chrome 43.0.2357.124 m. Updated the answer.
  • GµårÐïåñ
    GµårÐïåñ about 8 years
    I have confirmed that this works in many instances but still occasional stubborn ones but better than nothing, thank you. I will add it to the post.
  • swcool
    swcool over 7 years
    I had removed MarkView login function for users to access freely. So the example I mentioned in above is not available now.
  • Rotimi
    Rotimi about 7 years
    this is 2017 and i still get the error of "Scripts may not close windows that were not opened by script."
  • mt025
    mt025 about 7 years
    Just as a note: Not working for me in Greasemonkey 3.10
  • Jeff Clayton
    Jeff Clayton about 7 years
    @YumYumYum thanks for the post, bitbucket.org changed the link to bitbucket.io recently - fixed in the answer now
  • Bimal Das
    Bimal Das almost 7 years
    please give solution on your answer. please don't discuss problem only on your answer.
  • Gopal00005
    Gopal00005 almost 7 years
    Nice hack for confirm button of IE 11.
  • Subhajit
    Subhajit over 6 years
    Not working in latest chrome - Version 61.0.3163.100 (Official Build) (64-bit)
  • Vineeth Pradhan
    Vineeth Pradhan almost 6 years
    Works on Chrome and Firefox
  • Zach Saucier
    Zach Saucier about 5 years
    This doesn't appear to be working for me in Tampermonkey in Chrome any longer.
  • Brock Adams
    Brock Adams about 5 years
    @ZachSaucier, what exactly doesn't work? (Zanetu's hack? Something else? Under what exact conditions?) You may need to open a new question and provide a minimal reproducible example.
  • Zach Saucier
    Zach Saucier about 5 years
    @BrockAdams The example TamperMonkey script
  • krystonen
    krystonen almost 5 years
    It works for me (having a button on the page to close the window). What didn't work was : window.open('', '_self', ''); window.close(); but it worked with open(location, '_self').close();
  • Jeff Clayton
    Jeff Clayton almost 5 years
    @krystonen - Glad you tried this one, while the option the op had issues with may have worked in the past, security updates have made these workarounds a necessity.
  • Anton Menshov
    Anton Menshov about 4 years
    Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
  • Scott Christensen
    Scott Christensen about 4 years
    This hole looks to have been filled. I don't know as of when but I'm using the latest dev build 84.x. The blank page loads but the close does not fire.
  • user889030
    user889030 almost 4 years
    can u add proper instruction how to do it , am new to tampermonkey
  • GµårÐïåñ
    GµårÐïåñ over 3 years
    Interesting approach, will give a test when I can to see.
  • Ibnul Husainan
    Ibnul Husainan over 3 years
    don't forget to "destroy" your script too
  • Ayush Srivastava
    Ayush Srivastava over 3 years
    how to destroy the script?
  • Envek
    Envek over 3 years
    Thank you for sharing this bit of knowledge about kiosk mode. I can confirm this it works! And this is exactly what I actually want.
  • Larry Martell
    Larry Martell about 3 years
    I get same as @LordOfThePigs - the page is cleared out but the tab remains open.
  • Larry Martell
    Larry Martell about 3 years
    All this does is clear out the window, but does not close the tab.
  • Jeff Clayton
    Jeff Clayton about 3 years
    @LarryMartell To help you or anyone else reading this, there are 2 questions needing answers about your experience -- 1) what browser are you using on what device? 2) did you go to the opener test page or did you just try it without using a page to launch the window? (it cannot always close a window that was not opened with the script as javascript needs to open it to get a handle before attempting to close the new window.)
  • Rahul
    Rahul over 2 years
    After reading all the answers above, it seems nothing works including this answer too.
  • JOSAN THOMAS
    JOSAN THOMAS over 2 years
    This is not working for me. Window is not closing if it is open in self