skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. Here is a refactored method to accomplish the desired functionality albeit in a ‘pop up’ window:

    let myWindow;
    
            const width = document.getElementById('width');
            const height = document.getElementById('height');
    
            if (width && height) {
                width.innerHTML = "Window inner width is: " + window.innerWidth;
                height.innerHTML = "Window inner height is: " + window.innerHeight;
            }
    
            function openWindow() {
                myWindow = window.open('http://example.com', '', 'width=800,height=600');
            }
    
            function closeWindow() {
                if (myWindow && !myWindow.closed) {
                    myWindow.close();
                }
            }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search