Search code examples
javascriptbrowser-history

History API state code disables website functionality


I run the following code in facebook.com (either with Greasemonkey/Tampermonkey). The code hides the left navigation menu, available in your general wall.

My problem:

The code works, but after executing it I cannot access my faceook conversations page.

When navigating to the conversations page by clicking the messages icon, then, "See all in messenger", my conversations page appears as a blank page.

enter image description here


My code:

let utilityFunc = ()=>{
    let run = (run)=>{
        setInterval( ()=>{
            document.querySelectorAll('#left_nav_section_nodes, #pagelet_ego_pane, .ego_section').forEach((e)=>{
                e.remove();
            });
        }, 500);
    };

    let pS = window.history.pushState;
    let 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);
    };
};

utilityFunc();

My question

Why would this code cause that?


Solution

  • There are two ways to solve this.

    Way 1:

    I consulted a senior JS programmer about this and this is the solution he gave me. The code behaves basically the same but without the problem:

    let utilityFunc = ()=>{
        let run = ()=>{
            setInterval( ()=>{
                document.querySelectorAll('#left_nav_section_nodes, #pagelet_ego_pane, .ego_section').forEach((e)=> {
                    e.remove();
                });
                // alert('All selectors are valid so far and if they weren't, this entire module was failing');
            }, 250);
        };
    
        let pS = window.history.pushState.bind(window.history);
        let rS = window.history.replaceState.bind(window.history);
    
        window.history.pushState = (...args)=>{
            run();
            pS(...args);
        };
    
        window.history.replaceState = (...args)=>{
            run();
            rS(...args);
        };
    };
    
    utilityFunc();
    

    He told me that to understand this solution, one needs to learn about call(), apply() and bind() concepts (here's an article to cover these), and to understand spread syntax.

    Way 2 - the original way I could take:

    One can use CSS injection to inject CSS so to manipulate the selected elements via CSS.

    See this SE QA session for more data (see answers by Dan Krieger and user8551674).