I’m trying to use JavaScript to open and close a new window in my web application. The opening part works fine, but I’m having trouble closing the window using window.close().
Here’s my code:
let myWindow;
//select dom element
const width = document.getElementById('width');
const height = document.getElementById('height');
//show window object properties
width.innerHTML = "Window inner with is: " + window.innerWidth;
height.innerHTML = "Window inner height is: " + window.innerHeight;
function openWindow() {
myWindow = window.open('https://www.google.com')
}
function closeWindow() {
myWindow.close();
}
<div>
<input type="button" value="Open window" onclick="openWindow()" />
</div>
<div>
<input type="button" value="close window" onclick="closeWindow()" />
</div>
2
Answers
This is caused by a specific security HTTP header named as Cross-Origin-Opener-Policy.
Websites can specify this header to disallow actions to be performed by the opener (in this case your page), especially when it is cross-domain.
For Google specifically, they have specified
same-origin-allow-popups; report-to="gws"
in this header so you cannot perform any action since it is not in the same browsing context group.For websites without this HTTP header, the default is allow. You can try using
https://example.com
for example and it should work.Here is a refactored method to accomplish the desired functionality albeit in a ‘pop up’ window: