2

Lets say I want to go to the previous page in Chrome and I click "<-". Can I add an EventListener or some kind of function that activates when I click the button.

function goBack() {
  document.getElementsByTagName("body")[0].style.overflow = "auto";
}

So in the example above. I want to call goBack() function when user goes to previous page that changes body overflow to auto.

When I searched how to solve this problem I only found instances on how to move back using history.back().

George
  • 29
  • 2
  • Off of the top of my head, I could think of [`onBeforeUnload`](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event) – Rojo Nov 06 '22 at 17:40
  • Does this answer your question? [Call a JavaScript Function when Back Button of Browser is Clicked](https://stackoverflow.com/questions/12970627/call-a-javascript-function-when-back-button-of-browser-is-clicked) – Rojo Nov 06 '22 at 17:42
  • I don't think you can, because if you click the back button the browser loads a different page unless you will use History API. If that is the case you can use History API to listen to the change URL events. – jcubic Nov 06 '22 at 18:36

1 Answers1

1

Yes, this is possible. You could actually do this in either jQuery or plain JavaScript, based on your preference.

Here is how you would do it in jQuery:

$(window).unload(goBack);

Alternatively, here is javascript:

window.onbeforeunload = goBack;

That should do it!

Halo
  • 1,730
  • 1
  • 8
  • 31