YouTube not triggering history.pushState

て烟熏妆下的殇ゞ 提交于 2019-12-11 03:57:23

问题


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.



来源:https://stackoverflow.com/questions/30199242/youtube-not-triggering-history-pushstate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!