YouTube not triggering history.pushState

2019-07-21 18:29发布

问题:

I'm trying to detect a page change on YouTube by using history.pushState, but it never seems to trigger. I ultimately want to get this working from a Tampermonkey/Greasemonkey script, and for that I understand you need to inject the script into the actual page, which I've done like so, but to no avail:

html = 
    "var oldState      = history.pushState;"+
    "history.pushState = function() {" +
        "alert('url changed');" +
        "return oldState.apply(this);" +
    "}";

var head = document.getElementsByTagName("body")[0];         
var script = document.createElement('script');
script.type = 'text/javascript';
script.innerHTML = html;
head.appendChild(script);

I've also tried running the same code from the debug console:

var oldState      = history.pushState;
history.pushState = function() {
    alert('url changed');
    return oldState.apply(this);
};

But that didn't seem to do it either. Anyone have an idea of what's going on here?

回答1:

YouTube uses spfjs to manipulate pushState. However it grabs the function generally before you can monkey patch it. This is why you are experiencing the issue.

Either move your monkey patch script up in the page before spf.js is loaded, or you can look for the spf events like spfdone to detect the change.