Javascript bookmark stopped working in Firefox 13 - javascript

In Firefox version 13, bookmarklets (bookmarks with a javascript: URL, e.g. javascript: alert("it works") stopped working. Is there any solution to use javascript: bookmarks in Firefox 13?

This is a consequence of Bug 728313 - Using a bookmark keyword to a bookmarklet fails on new tabs, also Bug 739387 - Aurora 13a New Tab display doesn't allow javascript bookmarks to be selected . This bug affects Firefox 13 onwards.
As a consequence of the fix to bug 723808, javascript: bookmarks are disabled in a just-created new tab. If you first load almost any URL, including about:blank, then a Javascript bookmark will work in that tab.
Note that this is about Javascript bookmarks (bookmarklets). You cannot use this workaround to load javascript: URLs typed directly in the location bar. These have been disabled since Firefox 6, as a consequence of bug 656433 (phishing of javascript: URLs). Bug 680302 is a feature request to allow turning javascript: URLs back on through a preference. Valadrem has written the InheritPrincipal extension to remove this restriction (I haven't tested it). You can still type and run Javascript code in the Scratchpad (press Shift+F4, type code, press Ctrl+R).
There are restrictions on the Javascript you can run from the URL bar or from a bookmark. For example, since Firefox 7, you cannot resize the window (consequence of the fix to bug 565541); the services.sync.prefs.sync.dom.disable_window_move_resize controls this restriction.

NOTE: this solution no longer appears to work as of FF41. See JS Bookmarklets stopped working in Firefox 41.
If you first load almost any URL, including about:blank, then a
Javascript bookmark will work in that tab.
Since Firefox's default behavior for new tabs is about:newtab, which is nothing, and bookmarklets only run once something is loaded, you can do the following to set a default page, and then run bookmarklets:
open about:config
find browser.newtab.url
double-click and change from about:newtab to about:blank (or URI of your choice)
Ctrl-T and run bookmarklets in new tabs!

I have been able to use bookmarklets in recent versions of firefox (I just tested a few on FF23). Two suggestions:
Replace spaces with %20. For instance, try your example bookmarklet code with javascript:alert("it%20works") instead of javascript:alert("it works")
If this isn't enough, enclose the whole bookmarklet inside an anonymous function, so in your example, you'd write javascript:((function(){alert("it%20works");})())

Related

Is there really no way to close the browser? [duplicate]

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.
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.
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.
In tampermonkey now you can use
// #grant window.close
And then just simply call
window.close();
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" />
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!
Despite thinking it is "patently false", what you say "seems to be a belief" is actually correct. The Mozilla documentation for window.close says
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
You say that it is "supposed to still do it" but I don't think you'll find any reference which supports that, maybe you've misremembered something?
I found a new way that works for me perfetly
var win = window.open("about:blank", "_self");
win.close();
The below code worked for me -
window.open('location', '_self', '');
window.close();
Tested on Chrome 43.0.2357.81
This might be old, but let's answer it.
I use top.close() to close a tab. window.close() or other open...close didn't work for me.
In my case, the page needed to close, but may have been opened by a link and thus window.close would fail.
The solution I chose is to issue the window.close, followed by a window.setTimeout that redirects to a different page.
That way, if window.close succeeds, execution on that page stops, but if it fails, in a second, it will redirect to a different page.
window.close();
window.setTimeout(function(){location.href = '/some-page.php';},1000);
I wanted to share my "solution" with this issue. It seems like most of us are trying to close a browser window in a standard browser session, where a user is visiting some website or another, after they've visited other websites, and before they'll visit some more.
However, my situation is that I am building a web app for a device that will essentially be the only thing the device does. You boot it up, it launches Chrome and navigates to our app. It's not even connected to the internet, any servers it talks to are on our local Docker containers. The user needs a way to close the app (aka close Chrome) so they can access the terminal to perform system updates.
So it boots up, launches Chrome in kiosk mode, at the correct address already. This happens to easily satisfy the second option in the spec:
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 top-level browsing context whose session history contains only one Document.
So simply calling window.close() from my kiosk app just works!
If you can't close windows that aren't opened by the script, then you can destroy your page using this code:
document.getElementsByTagName ('html') [0] .remove ();
For those that are using an anchor tag to open the child window, this article describes a workaround for this issue.
My understanding is that in new versions of Chrome, the rel attribute is set to noopener by default for anchor tags with target _blank. So by setting it to opener you have the old behaviour back.
Please be aware that this was introduced to avoid tab-napping attacks.
Only if you open a new window using window.open() will the new window be able to close using code as I have mentioned above. This works perfectly for me :) Note : Never use href to open the page in a new tab. Window.close() does not work with "href" . Use window.open() instead.
You can also try to use my code below. This will also help you to redirect your parent window:
Parent:
<script language="javascript">
function open_a_window()
{
var w = 200;
var h = 200;
var left = Number((screen.width/2)-(w/2));
var tops = Number((screen.height/2)-(h/2));
window.open("window_to_close.html", '', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+tops+', left='+left);
return false;
}
// opener:
window.onmessage = function (e) {
if (e.data === 'location') {
window.location.replace('https://www.google.com');
}
};
</script>
<input type="button" onclick="return open_a_window();" value="Open New Window/Tab" />
Popup:
<!DOCTYPE html>
<html>
<body onload="quitBox('quit');">
<h1>The window closer:</h1>
<input type="button" onclick="return quitBox('quit');" value="Close This Window/Tab" />
<script language="javascript">
function quitBox(cmd)
{
if (cmd=='quit')
{
window.opener.postMessage('location', '*');
window.open(location, '_self').close();
}
return false;
}
</script>
</body>
</html>
For TamperMonkey:
#grant window.close
Ref: https://www.tampermonkey.net/documentation.php#_grant
Try something like this onclick="return self.close()"

window.close() self.close() not working in chrome version 59.0.3071.86 [duplicate]

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.
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.
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.
In tampermonkey now you can use
// #grant window.close
And then just simply call
window.close();
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" />
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!
Despite thinking it is "patently false", what you say "seems to be a belief" is actually correct. The Mozilla documentation for window.close says
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
You say that it is "supposed to still do it" but I don't think you'll find any reference which supports that, maybe you've misremembered something?
I found a new way that works for me perfetly
var win = window.open("about:blank", "_self");
win.close();
The below code worked for me -
window.open('location', '_self', '');
window.close();
Tested on Chrome 43.0.2357.81
This might be old, but let's answer it.
I use top.close() to close a tab. window.close() or other open...close didn't work for me.
In my case, the page needed to close, but may have been opened by a link and thus window.close would fail.
The solution I chose is to issue the window.close, followed by a window.setTimeout that redirects to a different page.
That way, if window.close succeeds, execution on that page stops, but if it fails, in a second, it will redirect to a different page.
window.close();
window.setTimeout(function(){location.href = '/some-page.php';},1000);
I wanted to share my "solution" with this issue. It seems like most of us are trying to close a browser window in a standard browser session, where a user is visiting some website or another, after they've visited other websites, and before they'll visit some more.
However, my situation is that I am building a web app for a device that will essentially be the only thing the device does. You boot it up, it launches Chrome and navigates to our app. It's not even connected to the internet, any servers it talks to are on our local Docker containers. The user needs a way to close the app (aka close Chrome) so they can access the terminal to perform system updates.
So it boots up, launches Chrome in kiosk mode, at the correct address already. This happens to easily satisfy the second option in the spec:
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 top-level browsing context whose session history contains only one Document.
So simply calling window.close() from my kiosk app just works!
If you can't close windows that aren't opened by the script, then you can destroy your page using this code:
document.getElementsByTagName ('html') [0] .remove ();
For those that are using an anchor tag to open the child window, this article describes a workaround for this issue.
My understanding is that in new versions of Chrome, the rel attribute is set to noopener by default for anchor tags with target _blank. So by setting it to opener you have the old behaviour back.
Please be aware that this was introduced to avoid tab-napping attacks.
Only if you open a new window using window.open() will the new window be able to close using code as I have mentioned above. This works perfectly for me :) Note : Never use href to open the page in a new tab. Window.close() does not work with "href" . Use window.open() instead.
You can also try to use my code below. This will also help you to redirect your parent window:
Parent:
<script language="javascript">
function open_a_window()
{
var w = 200;
var h = 200;
var left = Number((screen.width/2)-(w/2));
var tops = Number((screen.height/2)-(h/2));
window.open("window_to_close.html", '', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+tops+', left='+left);
return false;
}
// opener:
window.onmessage = function (e) {
if (e.data === 'location') {
window.location.replace('https://www.google.com');
}
};
</script>
<input type="button" onclick="return open_a_window();" value="Open New Window/Tab" />
Popup:
<!DOCTYPE html>
<html>
<body onload="quitBox('quit');">
<h1>The window closer:</h1>
<input type="button" onclick="return quitBox('quit');" value="Close This Window/Tab" />
<script language="javascript">
function quitBox(cmd)
{
if (cmd=='quit')
{
window.opener.postMessage('location', '*');
window.open(location, '_self').close();
}
return false;
}
</script>
</body>
</html>
For TamperMonkey:
#grant window.close
Ref: https://www.tampermonkey.net/documentation.php#_grant
Try something like this onclick="return self.close()"

How to close a html window using javascript? [duplicate]

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.
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.
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.
In tampermonkey now you can use
// #grant window.close
And then just simply call
window.close();
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" />
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!
Despite thinking it is "patently false", what you say "seems to be a belief" is actually correct. The Mozilla documentation for window.close says
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
You say that it is "supposed to still do it" but I don't think you'll find any reference which supports that, maybe you've misremembered something?
I found a new way that works for me perfetly
var win = window.open("about:blank", "_self");
win.close();
The below code worked for me -
window.open('location', '_self', '');
window.close();
Tested on Chrome 43.0.2357.81
This might be old, but let's answer it.
I use top.close() to close a tab. window.close() or other open...close didn't work for me.
In my case, the page needed to close, but may have been opened by a link and thus window.close would fail.
The solution I chose is to issue the window.close, followed by a window.setTimeout that redirects to a different page.
That way, if window.close succeeds, execution on that page stops, but if it fails, in a second, it will redirect to a different page.
window.close();
window.setTimeout(function(){location.href = '/some-page.php';},1000);
I wanted to share my "solution" with this issue. It seems like most of us are trying to close a browser window in a standard browser session, where a user is visiting some website or another, after they've visited other websites, and before they'll visit some more.
However, my situation is that I am building a web app for a device that will essentially be the only thing the device does. You boot it up, it launches Chrome and navigates to our app. It's not even connected to the internet, any servers it talks to are on our local Docker containers. The user needs a way to close the app (aka close Chrome) so they can access the terminal to perform system updates.
So it boots up, launches Chrome in kiosk mode, at the correct address already. This happens to easily satisfy the second option in the spec:
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 top-level browsing context whose session history contains only one Document.
So simply calling window.close() from my kiosk app just works!
If you can't close windows that aren't opened by the script, then you can destroy your page using this code:
document.getElementsByTagName ('html') [0] .remove ();
For those that are using an anchor tag to open the child window, this article describes a workaround for this issue.
My understanding is that in new versions of Chrome, the rel attribute is set to noopener by default for anchor tags with target _blank. So by setting it to opener you have the old behaviour back.
Please be aware that this was introduced to avoid tab-napping attacks.
Only if you open a new window using window.open() will the new window be able to close using code as I have mentioned above. This works perfectly for me :) Note : Never use href to open the page in a new tab. Window.close() does not work with "href" . Use window.open() instead.
You can also try to use my code below. This will also help you to redirect your parent window:
Parent:
<script language="javascript">
function open_a_window()
{
var w = 200;
var h = 200;
var left = Number((screen.width/2)-(w/2));
var tops = Number((screen.height/2)-(h/2));
window.open("window_to_close.html", '', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+tops+', left='+left);
return false;
}
// opener:
window.onmessage = function (e) {
if (e.data === 'location') {
window.location.replace('https://www.google.com');
}
};
</script>
<input type="button" onclick="return open_a_window();" value="Open New Window/Tab" />
Popup:
<!DOCTYPE html>
<html>
<body onload="quitBox('quit');">
<h1>The window closer:</h1>
<input type="button" onclick="return quitBox('quit');" value="Close This Window/Tab" />
<script language="javascript">
function quitBox(cmd)
{
if (cmd=='quit')
{
window.opener.postMessage('location', '*');
window.open(location, '_self').close();
}
return false;
}
</script>
</body>
</html>
For TamperMonkey:
#grant window.close
Ref: https://www.tampermonkey.net/documentation.php#_grant
Try something like this onclick="return self.close()"

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

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.
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.
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.
In tampermonkey now you can use
// #grant window.close
And then just simply call
window.close();
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" />
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!
Despite thinking it is "patently false", what you say "seems to be a belief" is actually correct. The Mozilla documentation for window.close says
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
You say that it is "supposed to still do it" but I don't think you'll find any reference which supports that, maybe you've misremembered something?
I found a new way that works for me perfetly
var win = window.open("about:blank", "_self");
win.close();
The below code worked for me -
window.open('location', '_self', '');
window.close();
Tested on Chrome 43.0.2357.81
This might be old, but let's answer it.
I use top.close() to close a tab. window.close() or other open...close didn't work for me.
In my case, the page needed to close, but may have been opened by a link and thus window.close would fail.
The solution I chose is to issue the window.close, followed by a window.setTimeout that redirects to a different page.
That way, if window.close succeeds, execution on that page stops, but if it fails, in a second, it will redirect to a different page.
window.close();
window.setTimeout(function(){location.href = '/some-page.php';},1000);
I wanted to share my "solution" with this issue. It seems like most of us are trying to close a browser window in a standard browser session, where a user is visiting some website or another, after they've visited other websites, and before they'll visit some more.
However, my situation is that I am building a web app for a device that will essentially be the only thing the device does. You boot it up, it launches Chrome and navigates to our app. It's not even connected to the internet, any servers it talks to are on our local Docker containers. The user needs a way to close the app (aka close Chrome) so they can access the terminal to perform system updates.
So it boots up, launches Chrome in kiosk mode, at the correct address already. This happens to easily satisfy the second option in the spec:
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 top-level browsing context whose session history contains only one Document.
So simply calling window.close() from my kiosk app just works!
If you can't close windows that aren't opened by the script, then you can destroy your page using this code:
document.getElementsByTagName ('html') [0] .remove ();
For those that are using an anchor tag to open the child window, this article describes a workaround for this issue.
My understanding is that in new versions of Chrome, the rel attribute is set to noopener by default for anchor tags with target _blank. So by setting it to opener you have the old behaviour back.
Please be aware that this was introduced to avoid tab-napping attacks.
Only if you open a new window using window.open() will the new window be able to close using code as I have mentioned above. This works perfectly for me :) Note : Never use href to open the page in a new tab. Window.close() does not work with "href" . Use window.open() instead.
You can also try to use my code below. This will also help you to redirect your parent window:
Parent:
<script language="javascript">
function open_a_window()
{
var w = 200;
var h = 200;
var left = Number((screen.width/2)-(w/2));
var tops = Number((screen.height/2)-(h/2));
window.open("window_to_close.html", '', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+tops+', left='+left);
return false;
}
// opener:
window.onmessage = function (e) {
if (e.data === 'location') {
window.location.replace('https://www.google.com');
}
};
</script>
<input type="button" onclick="return open_a_window();" value="Open New Window/Tab" />
Popup:
<!DOCTYPE html>
<html>
<body onload="quitBox('quit');">
<h1>The window closer:</h1>
<input type="button" onclick="return quitBox('quit');" value="Close This Window/Tab" />
<script language="javascript">
function quitBox(cmd)
{
if (cmd=='quit')
{
window.opener.postMessage('location', '*');
window.open(location, '_self').close();
}
return false;
}
</script>
</body>
</html>
For TamperMonkey:
#grant window.close
Ref: https://www.tampermonkey.net/documentation.php#_grant
Try something like this onclick="return self.close()"

Create a Bookmark link that works in Safari

I have tried using JavaScript "AddFavorite" function in my code, but it does not work in Safari. It works in IE, I think I remember Firefox, but nothing I have tried seems to work in Safari. All I want to do is have a link on my website that people can click on and it automatically creates a bookmark in their bookmarks folder/bookmark bar.
Does this entail Applescript or something like it? Or a deeper programming language I am unaware of?
<a href="javascript:bookmarksite('Name', 'website.com')">
From the apple forums: forum-link
On the Mac side at least, Safari does not allow a website to add a
bookmark. I'm pretty sure the same behaviour is in the Windows version
as well.
I've been down this road, and what I discovered was that Safari does NOT allow bookmarks to be made with JavaScript:
Apple Forum
bytes forum
They consider it unsafe. As frustrating as this is, I get their point.
Unfortunately, most things like this tend to be browser-specific, and picky.
my JS is about level 0, but i did find this on an old article here:
One specifically for Chrome:
Add to favourites link for Google Chrome
And another on a cross-browser bookmark link:
Cross-browser bookmark/add to favorites javascript
Hope between the previous comment and these links, you get what you needed.
Chrome and Safari does not allow it for clear security reason.
You could usee a script like this:
http://www.dynamicsitesolutions.com/javascript/add-bookmark-script/
which handles many browser and has a nice fallback: show a browser customized alert with instructuion message.
Es: in chrome it says: "Ctrl+D to add as bookmark"
In IE something similar to the following would work: (MSDN)
window.external.AddFavorite(location.href, document.title);
However, this won't work in other browsers. In Firefox, I believe you can use
window.sidebar.addPanel(document.title, location.href, '');
to create a sidebar panel (not a real bookmark) but as far as I know Chrome and Safari do not allow Javascript to automatically create bookmarks. For those, I recommend giving the user the instructions to do it manually:
drag a link to their bookmarks
pressing Ctrl + D to add a bookmark
Clicking + or star icon in the toolbar

Categories

Resources