Implementing Backward and Forward buttons of Browser in JavaScript

Thamaraiselvam - Apr 16 '19 - - Dev Community

I have been thinking about the real-time example of stack data structure and found this question on StackOverflow.

A history of pages viewed is kept in a stack-like form

And I implemented the same on JavaScript. It took me like 30 minutes to do it

I have two stacks Forward Stack, Backward Stack and one variable to hold current state.

this.forwardStack = [];
this.backwardStack = [];
this.currentURL = '';

Problem solution

  • When user visit URL Second time pushes the current URL into Backward State.
  • If Backward button clicked push Current URL into Forward Stack and pop the last URL from backward Stack and set as Current State
  • If Forward button clicked push Current URL into Backward Stack and pop the last URL from Forward Stack and set as Current State

I chunked the problem into 3 tasks such as,

  • Add New URL
  • Go Backward
  • Go Forward
Add New URL
addNewURL(url) {
    if (this.currentURL) {
        this.backwardStack.push(this.currentURL);
    }
    this.currentURL = url;
}

If User visits URL for the First time then Add it to CurrentURL, If second URL comes in then push the current URL into Backward Stack and replace the Current URL.

Go Backward
goBackward() {
    if (!this.backwardStack.length) {
        return;
    }

    this.forwardStack.push(this.currentURL);
    this.currentURL = this.backwardStack.pop();
}

On clicking Backward button push current URL into Forward Stack and pop the last URL From Backward Stack and make it as currentURL and If the stack is empty then just return.

Go Forward
goForward() {
    if (!this.forwardStack.length) {
        return;
    }

    this.backwardStack.push(this.currentURL);
    this.currentURL = this.forwardStack.pop();
}

On clicking Forward button push current URL into Backward Stack and pop the last URL From Forward Stack and make it as currentURL and If the stack is empty then just return.

Hurray!

That's it we have implemented Browser's Backward and Forward buttons in JavaScript.

I wrote a test case also for this.

Navigation Stack.PNG

Here is Github Repo for full source code.

This post published on Hashnode Story, I love to hear your feedback and do not forget to correct me if I am wrong anywhere.

. . . . . . . . . . . . . . .