【发布时间】:2015-05-12 18:54:40
【问题描述】:
我正在尝试使用 history.pushState 检测 YouTube 上的页面更改,但它似乎从未触发。我最终希望通过 Tampermonkey/Greasemonkey 脚本来实现这一点,为此我知道您需要将脚本注入到实际页面中,我已经这样做了,但无济于事:
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);
我也尝试从调试控制台运行相同的代码:
var oldState = history.pushState;
history.pushState = function() {
alert('url changed');
return oldState.apply(this);
};
但这似乎也没有用。有人知道这里发生了什么吗?
【问题讨论】:
-
是什么让您认为
history.pushState会检测到变化?该方法添加到历史记录。 检测变化需要监听popstate事件。 -
我正在重写该函数,或者至少是这样的想法。
onpopstate似乎仅在按下后退和前进按钮时触发(根据我的测试)。见stackoverflow.com/a/4585031/1107110 -
啊,好的。您是否首先检查过您的脚本插入是否真的有效?就像尝试在其中放置
console.log语句一样,看看是否会产生预期的输出…… -
是的,脚本插入没问题。
-
而
console.log(history.pushState)(在覆盖之前)会产生什么?
标签: javascript youtube html5-history