Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum call stack sizeexceed with popstate

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

Step by step :

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

Step 2 : I clicked on backtohome button. addToHistory() works great

Step 3 : I clicked on the forward button, I bind window.popstate and at the line window.location I have an infinite loop. And I don't see the next page.

What's wrong with 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();
like image 847
Steffi Avatar asked Jul 10 '26 22:07

Steffi


1 Answers

The problem is that setting window.location is triggering another popState event, therefore setting window.location again, therefore calling a popState event...

like image 99
spro Avatar answered Jul 13 '26 15:07

spro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!