wantToLearn
wantToLearn

Reputation: 21

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

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> 

Upvotes: 2

Views: 1736

Answers (2)

Abhishek Kumar
Abhishek Kumar

Reputation: 564

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.

Upvotes: 2

user9783773
user9783773

Reputation:

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();
    }
}

Upvotes: 2

Related Questions