'window.close() doesn't work - Scripts may close only the windows that were opened by it
I'm having a problem always when I'm trying to close a window through the window.close() method of the Javascript, while the browser displays the below message on the console:
"Scripts may close only the windows that were opened by it."
This occurs in every part of the page. I can run this directly of a link, button, or a script, but this message always are displayed.
I'm tried to replace the window.close(); method for the functions (or variants of these) below, but nothing happened again:
window.open('', '_self', '');
window.close();
Solution 1:[1]
Error messages don't get any clearer than this:
"Scripts may close only the windows that were opened by it."
If your script did not initiate opening the window (with something like window.open), then the script in that window is not allowed to close it. Its a security to prevent a website taking control of your browser and closing windows.
Solution 2:[2]
You can't close a current window or any window or page that is opened using '_self' But you can do this
var customWindow = window.open('', '_blank', '');
customWindow.close();
Solution 3:[3]
There is no permanent fix even though someone answered this the code still breaks adventually its basically just a useless java script feature
Solution 4:[4]
Ran into this issue but I was using window.open('','_blank',''). The issue seems to be that the script that used window.open should also call the close function.
I found a dirty yet simple workaround that seems to get the job done -
// write a simple wrapper around window.open that allows legal close
const openWindow = () => {
const wind = window.open('','_blank','');
// save the old close function
const actualClose = wind.close;
// Override wind.close and setup a promise that is resolved on wind.close
const closePromise = new Promise(r=>{wind.close = ()=>{r(undefined);}});
// Setup an async function
// that closes the window after resolution of the above promise
(async ()=>{
await closePromise; // wait for promise resolution
actualClose(); // closing the window here is legal
})();
return wind;
}
// call wind.close anywhere
document.getElementById('myButton').addEventListener('click', wind.close)
I don't know if this somehow defeats some security feature or if this will be patched later but it does seem to work on chrome version 101.0.4951
Solution 5:[5]
The windows object has a windows field in which it is cloned and stores the date of the open window, close should be called on this field:
window.open("", '_self').window.close();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | somethinghere |
| Solution 2 | andrex |
| Solution 3 | developer |
| Solution 4 | gudCoder |
| Solution 5 | Cananau Cristian |
