Maximum call stack size with popstate

I tried to use the function popstate, but I have an error:Uncaught RangeError: Maximum call stack size exceeded

Step by step :

Step 1: I clicked on li. addToHistory () works fine.

Step 2: I pressed the button backtohome. addToHistory () works fine

Step 3: I clicked the “forward” button, I bind window.popstateand in line window.locationI have an infinite loop. And I do not see the next page.

What happened to my function?

function addToHistory(url) {
      window.history.pushState(null, " ", url);
}

$("li").on("click", function(e){
      var name = this_li.attr("data-name");
      addToHistory("#" + name); // example http://azerty.com/#kevin
      ...
}

$("#backtohome").on("click", function(){
      addToHistory("http://azerty.com/");
      ...
}

function hash(){
     var popped = ('state' in window.history && window.history.state !== null), 
             initialURL = location.href;

     $(window).bind('popstate', function (event) {
        // Ignore inital popstate that some browsers fire on page load
        var initialPop = !popped && location.href == initialURL
        popped = true
        if (initialPop) return;

        window.location = window.location.href;
        return;

     });
 }

 hash();
+3
source share
2 answers

The problem is that setting window.location raises another popState event, so it sets window.location again, so it raises the popState event ...

+4
source

, "location.href= location.href;" popstate

0

All Articles