sangoko sangoko - 2 months ago 18
Javascript Question

Pushing a state to page history and then replacing an existing state with it

I found this 18 rows Javascript code that as I understand, pushes a state to the memory, and then replaces it with another existing state, so that the webpage's DOM content will change. The code uses to replace data that was loaded with AJAJ instead directly from PHP (given that setTimeout and setInterval didn't help to change it).

var run = (run)=> {
// insert your code here
};

var pS = window.history.pushState;
var rS = window.history.replaceState;

window.history.pushState = (a, b, url)=> {
run(url);
pS.apply(this, arguments);
};

window.history.replaceState = (a, b, url)=> {
run(url);
rS.apply(this, arguments);
};

})();


There is an
unrecoverable syntax error
in line 16 (
};
). Why is it there? As a JS newbie I don't have the slightest idea - I read about closures and tried to read the code about 4 times but didn't recognize anything wrong with the closures, and I tried to look for syntax errors or typos in keywords/names/syntax but didn't find any.

I feel as something is wrong with the logic of the code and that in this stage of my studies, I think I lack enough knowledge to find the problem.

Answer Source

The last line has a } and a ) that is not paired with an opening { and (.

My Conclusion:

  1. They were placed there by mistake
  2. You did not include the entire file/code
  3. Or they are part of an IIFE (Immediately Invoked Function Expression) that is missing its opening

I'll assume Number 3, and provide the solution to Number 3

(function(){
    var run = (run)=> {
       // insert your code here
    };

    var pS = window.history.pushState;
    var rS = window.history.replaceState;

    window.history.pushState = (a, b, url)=> {
        run(url);
        pS.apply(this, arguments);
    };

    window.history.replaceState = (a, b, url)=> {
        run(url);
        rS.apply(this, arguments);
    };

})();

As you can see on line 1, I added (function(){ to match the closing bracket and parenthesis