سؤال

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();
هل كانت مفيدة؟

المحلول

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

نصائح أخرى

I faced a similar problem and resolved it by removing "location.href = location.href;" in popstate event

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top