2

My question is related to this post: Javascript : History back() Method

I want to implement a "back" button on my website. But lets imagine the page was opened in a new tab.

Is there a way to close the window, if the browser history is empty?

I am kinda struggling to connect the history.back() and window.close() function but that's all I ve got to do, isn't it?

appreciate your help!

BB23
  • 173
  • 9
  • Every tab (or window) has it's own history object, which is empty at the time you're first opening the tab. – Teemu Jan 27 '20 at 11:39
  • 1
    See my comment on @Titulum answer. If you're not opening the window using `window.open()`, you're not going to to be able to close it using `window.close()` – Brett Gregson Jan 27 '20 at 11:42
  • I would suggest you to create your own history object, so whenever you opened any tab/window add it in your object and when user press back or next then close/open window. – Sameer Jan 27 '20 at 11:58
  • The above suggestion will only work, if user is navigating with your website's buttons, otherwise browsers back/next will be different for window as @Teemu said – Sameer Jan 27 '20 at 12:00

2 Answers2

3

According to this StackOverflow post, it is not possible to definitely determine whether there are still browser history entries or not. Thus, @Titulum's solution should work but could fail depending on the browser implementation of the History API.

SparkFountain
  • 2,110
  • 15
  • 35
1

You could use a method like this:

function closeWindowIfHistoryIsEmpty() {
  if (window.history.length === 0) {
    window.close();
  } else {
    window.history.back();
  }
}
Titulum
  • 9,928
  • 11
  • 41
  • 79
  • 3
    Technically this will work, but OP needs to keep in mind that `window.close()` will only close windows that were opened by `window.open()` : https://developer.mozilla.org/en-US/docs/Web/API/Window/close – Brett Gregson Jan 27 '20 at 11:40
  • Ok it is as you said. The code is technically working but, as I am not using the window.open() function, it is not working as expected... – BB23 Jan 27 '20 at 11:53