beNerd beNerd - 3 months ago 16
Javascript Question

Close a window opened with window.open() after clicking a button

I have a simple case here:

I use

window.open('http://remoteserver.com/success')
to open a window in the browser like this:

const win = window.open('http://remoteserver.com/success')


Now the remote server sends an HTML like this:

<!DOCTYPE html>
<html lang="en">
<body>
<div class="row text-center" style="margin-top:50px">
Success!
<button type="button" class="btn btn-primary" onclick="closeWindow()">Go Back</button>
</div>
</body>
<script >
function closeWindow(e)
{
this.close()
console.log(e);
}
</script>
</html>


Now when a user clicks on the "go back" button, it shows a warning that windows can only be closed by a script who opened it!

How do I close such window?

WHAT I TRIED

script that opens the popup:

iabRef = window.open( 'https://api.mydomainxxx.com/test', '_blank', 'location=no' );
window.addEventListener( 'message', event => {
if ( event.origin === 'https://api.mydomainxxx.com' ) {
if ( data === 'close' ) iabRef.close()
}
} )


script that returns from the server:

<body>
<div class="row text-center" style="margin-top:50px">
<h2 class="warning">Payment Successful</h2>
<button type="button" class="btn btn-primary">Go Back</button>
</div>

</body>

<script>
document.querySelector('button').addEventListener('click', () => {
// Only send messages to http://example.com.

window.parent.postMessage('close', 'https://api.mydomainxxx.com');
})

</script>

Answer

You can use window.postMessage() to post a message to the parent window, and in the parent window listen for messages and close the window when you get a message.

const win = window.open('http://example.com/success')
window.addEventListener('message', event => {
  // Only accept messages from http://example.com.
  if (event.origin === 'http://example.com') {
    if (data === 'close') win.close()
  }
})

The HTML file:

<!DOCTYPE html>
<html lang="en">
  <body>
  <div class="row text-center" style="margin-top:50px">
    Success!
    <button type="button" class="btn btn-primary">Go Back</button>
  </div>
  </body>
  <script>
    document.querySelector('button').addEventListener('click', () => {
      // Only send messages to http://example.com.
      window.opener.postMessage('close', 'http://example.com')
    })
  </script>
</html>