Egidi
Egidi

Reputation: 1776

Javascript | Check if a windows with specific URL already is opened

This functions show a /ticket.html popup window.

I need to check before if the window is already opened. If it is, cancel the new openning.

How could this be done?

function popitup() {
           newwindow=window.open("ticket.html","_blank","toolbar=yes,scrollbars=yes, resizable=yes, top=500, left=500, width=730, height=700");
           newwindow.moveTo(350,150);
       if (window.focus) 
              {
                 newwindow.focus()
              }
      }

Regards,

Upvotes: 0

Views: 8259

Answers (2)

paulojreis
paulojreis

Reputation: 51

You may save a reference to the window, when opening it. The window.open method returns a windowObjectReference.

With this reference, you can check if the window is closed (closed property, a boolean) or simply if the window is null (window property, which will be a Window object or null, if closed).

Simple example:

// Open the pop-up and save the reference.
var windowObjRef = window.open('ticket.html');

// Verification, alternative 1. You may encapsulate this in a method.
if (windowObjRef.closed) {
    // The window is closed.
else {
    // The window is still open.
}

// Verification, alternative 2. You may encapsulate this in a method.
if (windowObjRef.window) {
    // The window is still open.
else {
    // The window is closed.
}

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window

Upvotes: 1

ryanafrish7
ryanafrish7

Reputation: 3410

I'm new to javascript. I found a website giving the following code. But it gives information on only whether the window is created earlier or not.

function myOpenWindow(winURL, winName, winFeatures, winObj)
{
  var theWin; // this will hold our opened window 

  // first check to see if the window already exists
  if (winObj != null)
  {
    // the window has already been created, but did the user close it?
    // if so, then reopen it. Otherwise make it the active window.
    if (!winObj.closed) {
      winObj.focus();
      return winObj;
    } 
    // otherwise fall through to the code below to re-open the window
  }

  // if we get here, then the window hasn't been created yet, or it
  // was closed by the user.
  theWin = window.open(winURL, winName, winFeatures); 
  return theWin;
}

Also, accessing the contents of other tabs may also bring attack on privacy of the user.

Upvotes: 1

Related Questions