How can i close tab or reopen popup tab in javascript?

1.5k Views Asked by At

I am trying to get the reference of the newly opened tab and use it in the same function to close the tab and reopen, for more details: I want to create a Java script button

  1. on the first click open a new tab
  2. on the second click of the same button close the tab and reopen the same tab

var Window; 
// Function that open the new Window 
function windowOpen() { 
  Window = window.open( "https://www.google.com/", "_blank", "width=400, height=450"); 

  // if (window.opener) {
  //     window.opener.announceWindow( window );
  // }
}
// function announceWindow( win ) {
//     window.close();
// }
<button onclick="windowOpen()" target=_blank> 
    Open Window
</button> 

2

There are 2 best solutions below

0
AudioBubble On

You could use something like this:

let google;
let open = false;
function toggleWindow() {
    open = !open;
    if (open) {
        google = window.open("https://www.google.com/", "_blank", "width=400, height=450");
    } else {
        google.close();
    }
}
0
Abhishek Kumar On

You can do like this:

var Window = window.open('https://www.google.com');
function windowOpen() {
  if(Window !== null){
      alert("Window alreay open");
      Window.close();
      Window = null;
  }else {
    Window = window.open('https://www.google.com');
  }
}
<button onclick="windowOpen()">
  Open Window
</button>

open() function opens a new tab. It's name property has _blank value by default. But if you close the tab manually, then you have to refresh the page to work JS properly otherwise you will get alert "Window already open" even after the closing of the tab.