2

Is it possible to open a new tab only if it is not already open.

index.php

$('.title').on('click', function(){
    if tab `images.php` is already open -> go to that tab
    else {window.open('images.php', '_blank')  // open a new tab
});

So I don't want to open a new tab if it already exists.

In both cases, current tab (index.php) stays as open, but it's not active.

  • Related question which may be helpful (if it's not a duplicate): https://stackoverflow.com/questions/23690666/check-if-my-website-is-open-in-another-tab – TimSch Nov 17 '18 at 20:35

2 Answers2

2

Just give the window a name and also make sure that doesn't start with an underscore, otherwise it will behave like html's _target attribute:

$('.title').on('click', function(){
  window.open('images.php', 'myWindow')
  // it will open the same window on following clicks
});

If you don't want to reload the page:

var myWindow = null;
$('.title').on('click', function(){
  if(myWindow == null || myWindow.closed)
    myWindow = window.open('images.php', 'myWindow')
  else
    myWindow.focus()
});

You may read more about window.open in the docs.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
0

Copied from MDN window.open() docs "Best Practices" section

var windowObjectReference = null; // global variable

function openFFPromotionPopup() {
  if(windowObjectReference == null || windowObjectReference.closed)
  /* if the pointer to the window object in memory does not exist
     or if such pointer exists but the window was closed */

  {
    windowObjectReference = window.open("http://www.spreadfirefox.com/",
   "PromoteFirefoxWindowName", "resizable,scrollbars,status");
    /* then create it. The new window will be created and
       will be brought on top of any other window. */
  }
  else
  {
    windowObjectReference.focus();
    /* else the window reference must exist and the window
       is not closed; therefore, we can bring it back on top of any other
       window with the focus() method. There would be no need to re-create
       the window or to reload the referenced resource. */
  };
} 
charlietfl
  • 170,828
  • 13
  • 121
  • 150