-2

I’m trying to implement back-click, go back in the browser to the specified link, the problem is that the method only works when the user clicks.

window.onpopstate = function(event) {
 event.preventDefault();
 window.open('file://............');
};
history.pushState({questionID: '555'}, null, null);
Dmitry
  • 1
  • 1
  • Correct me if im wrong but you have a button to get to one page, and from that one page you'd like the same button to take you back to the previous page? – Hrittik Chatterjee Jul 15 '20 at 19:13
  • No, there are browser buttons (back and forth). As soon as I first open the page, and immediately want to click the browser button back, I’m not going to the beginning of the browser, but on the link that I indicated. @HrittikChatterjee – Dmitry Jul 15 '20 at 19:20
  • `history.go(-1)` will take the user back one step in the history without a button click. It's quite confusing what you are trying to do though. – Heretic Monkey Jul 15 '20 at 19:34
  • This looks really bizarre. I can't see any good reason to write code like this. Are you trying to work around the prohibition on opening new windows without the user interacting with the page that is opening the new window? – Quentin Jul 15 '20 at 20:15

1 Answers1

-1

This can be done but goes against the expected browser behaviour; if you click back, you expect to return to the previous page.

With that said, you can take advantage of window.history to get the required result

var currentTitle = document.title,
    currentUrl   = window.location.href;

window.history.pushState({questionID: '555'}, "Question 555", "/go-back/here");
window.history.pushState({}, currentTitle, currentUrl);

window.onpopstate = function(){
    // handle clicking back here - generally do reload as it will do a proper load of the page
    window.location.reload(true);
}

NOTE: you can only pushState for urls on the same domain (i.e. same website) that you are currently on

Rylee
  • 1,481
  • 1
  • 6
  • 9
  • This is similar to my code, the question is that the transition is carried out immediately on the first click, and not on the second click, having previously made the first click on the page. – Dmitry Jul 16 '20 at 10:05
  • @Dmitry have you tried the code? Each push sets the `current` state i.e. pressing back goes to the previous page, not the one just pushed. The first push sets the state to the page you want to go "back" to, the next one sets to the current page. This means clicking back `once` will make it reload the first state - hence labelled `/go-back/here` – Rylee Jul 17 '20 at 05:42
  • the task is that when you click it for the first time, the transition will be made through the specified link, and not back through history. – Dmitry Jul 18 '20 at 11:03
  • @Dmitry so all you want to do is go to a url when clicking a button? – Rylee Jul 19 '20 at 22:14