2

I'm implementing a "Go Back" button that redirect the user to the previous page or close the current tab if the page is opened in a new tab.

How can i detect (server side or client side) if the page is opened in a new tab ?

My solution is to pass a parameter (for exemple "new_tab=1") in every href attribute of each <a> tag with target="_blank" so i can read that parameter in the page load event, but i hope in a quicker solution.

dev
  • 118
  • 2
  • 9

1 Answers1

2

You can look at the history.length property to see the length of pages in the stack, with history.length === 1 meaning a new tab.

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

dotconnor
  • 1,736
  • 11
  • 22
  • 1
    I don't see how this would indicate if the client has opened the new page in a new tab. What if once the new tab is opened, the user navigates? – Scott Marcus Nov 21 '18 at 19:04
  • Well once the user navigates, the tab wouldn't be considered a new tab and therefore the OP's Go Back button should work. – dotconnor Nov 21 '18 at 19:08
  • OP says that clicking back in a window that was opened in a new tab should close the window. So, if a new tab opens and the user navigates and then clicks back, the window should close. In your case, they would just go back to the previous page. – Scott Marcus Nov 21 '18 at 19:10
  • The way I read the OP's question is if there is no page to go back to, then the tab should close. I'm sorry if that's not the way you read it. – dotconnor Nov 21 '18 at 19:11
  • *or close the current tab if the page is opened in a new tab* – Scott Marcus Nov 21 '18 at 19:12
  • Scott Marcus's interpretation is correct. The most common scenario is a full postback in the opened page that increments `history.length`. Now i'm searching a way to link informations to a specific tab... – dev Nov 23 '18 at 16:41