我正在编写一个 Chrome 扩展程序,为 GitHub 上的任何页面(即任何与 https://github.com/*
匹配的 URL)提供内容脚本。
我只是尝试在每次加载 GitHub 上的页面时将一些内容记录到控制台,如下所示:
window.onload = function() {
console.log("LOAD");
};
此监听器函数在第一次加载 GitHub 页面时执行,但如果用户从那里导航到 GitHub 上的其他页面(通过单击链接或通过其他方式),则它不会触发。为什么? :(
重现步骤:
- 打开 GitHub 上任意存储库的页面 ( example )。您应该会看到控制台中记录的消息。
- 单击该页面上的任何链接。加载新页面时,不会记录任何消息。 :(
如何解决这个问题?
最佳答案
GitHub 似乎使用 AJAX(以及 history.pushState
)来加载网站的某些部分,因此 onload
仅在页面真正加载时才会触发,但是通过 AJAX 加载内容时不会。
由于 GitHub 在 AJAX 内容加载完成时使用 pushState
更改 URL,因此您可以检测到这种情况何时发生,并执行您的代码。
现在实际上并没有在使用 pushState
时触发的 native 事件,但有这个 little hack :
(function(history){
var pushState = history.pushState;
history.pushState = function(state) {
if (typeof history.onpushstate == "function") {
history.onpushstate({state: state});
}
return pushState.apply(history, arguments);
}
})(window.history);
所以,运行它,然后,您可以执行以下操作,而不是 window.onload
:
history.onpushstate = function () {
console.log("LOAD");
};
并非所有 GitHub 页面都以这种方式加载(AJAX + PushState
),因此您必须同时使用 window.onload
和 history.onpushstate
.
此外,您应该使用 window.addEventListener('load', fn);
而不是 window.onload
,因为您不知道 GitHub 的代码是否可以覆盖window.onload
。
关于javascript - 如何在每次页面加载时执行内容脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29862056/