Send User To Previous Page in JavaScript

- 1 minute read

You can use the window.history object in JavaScript to send the user to the previous page in their browser:

const goBack = () => {
    if (typeof window.history !== `undefined`) {
        window.history.back();
    }
};

The above snippet uses the back method of window.history, which just sends the user to the last page.

But if you want to send the user to the second to last page (or any previous page), you can use the go method and pass in a negative integer that indicates how far you want to go back.

This modified goBack function accepts a numPages variable that is made negative and passed to window.history.go:

const goBack = (numPages) => {
    if (typeof window.history !== `undefined`) {
        window.history.go(-Math.abs(numPages));
    }
};

Here is some example usage of this extended function:

goBack(1); // Go to the previous page

goBack(2); // Go to the second to last page

goBack(3); // Go to the page before the second to last page

// etc.

Link to this section Conclusion

Anyway, that’s how you can send the user to an earlier page in their browsing history, using JavaScript.

I hope one of these snippets helped!