Best way to ensure links open in the same new window

This seems like it shouldn’t be a difficult task, but I just can’t get my brain to grasp it.

I’m required to have links open in a new window, after first checking whether or not the window is already open.

If the window is open, it should be closed then reopened with the new page loaded.

Personally, I don’t see why it needs to be closed and reopened instead of just reloaded, but that’s what’s required for this task.

I feel like window.open(), window.close() and window.closed are involved, as well as a named window, but I can’t workout how the correct code to implement this. Maybe I’m completely wrong?

I thought of putting the url inside the window.open() as well as the href, but is that unnecessary?

Is there a way to use the href inside of window.url(), or send it there? If I don’t use an href and target in the <a> that will cause them to be non-functional for users with Javascript disabled right? Should I be using ‘this’ keyword?

Any help would be much appreciated.

Stripped down code is as follows:

items-list.html

<a href=“show-item.html?name=Shirt&price=30 onclick=“checkWindowStatus();”>
<a href=“show-item.html?name=Hat&price=10 onclick=“checkWindowStatus();”>
<a href=“show-item.html?name=Socks&price=5 onclick=“checkWindowStatus();”>

show-item.js

var itemWindow;

function checkWindowStatus() {

// if window is already open
 if (!itemWindow.closed) {

  // close the window
  itemWindow.close();
  // open the window again with the new URL
  window.open(‘URL’, ‘itemWindow’);

 } else { // window isn’t already opened

  // open the window
  window.open(‘URL’, ‘itemWindow’);

 }

}

I’m not sure why you need the window to be ‘new’… Why not just load the new URL in the existing secondary window?

If they have javascript disabled, you won’t be able to do any of what you’re trying to do, as it’s all javascript.

1 Like

Hi @debstaaa, if you specify a name in window.open(), and a window with that name already exists, then the new URL will be loaded in that window. If you must close the existing window first as per your requirements, you have to keep a reference to that window – you’re almost there with your code, but you’re not setting itemWIndow anywhere which should actually throw an error when trying to check for itemWindow.closed. So it might look something like this:

var itemWindow

function checkWindowStatus (event) {
  event.preventDefault()

  if (itemWindow) {
    itemWindow.close()
  }

  itemWindow = window.open(event.target.href, 'itemWindow')
}

document.querySelectorAll('.item').forEach(function (item) {
  item.addEventListener('click', checkWindowStatus)
})
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.