【问题标题】:How to execute a content script every time a page loads?每次页面加载时如何执行内容脚本?
【发布时间】:2015-04-25 06:54:42
【问题描述】:

我正在编写一个 Chrome 扩展程序,它为 GitHub 上的任何页面提供内容脚本(即任何与 https://github.com/* 匹配的 URL)。

我只是想在每次 GitHub 上的页面加载时将一些内容记录到控制台,如下所示:

window.onload = function() {
  console.log("LOAD");
};

第一次加载 GitHub 页面时会执行此侦听器函数,但如果用户从那里导航到 GitHub 上的其他页面(通过单击链接或通过其他方式),它不会触发。为什么? :(

重现步骤:

  1. 在 GitHub (example) 上打开任何存储库的页面。您应该会看到记录到控制台的消息。
  2. 单击该页面上的任何链接。加载新页面时,不会记录任何消息。 :(

我该如何解决这个问题?

【问题讨论】:

    标签: javascript github google-chrome-extension content-script document-ready


    【解决方案1】:

    似乎 GitHub 使用 AJAX(连同 history.pushState)来加载网站的某些部分,因此 onload 只会在页面真正加载时触发,而不是在通过 AJAX 加载内容时触发。

    由于 GitHub 在 AJAX 内容加载完成时使用pushState 更改 URL,因此您可以检测到何时发生这种情况并执行您的代码。 现在实际上并没有在使用 pushState 时触发的原生事件,但是有这个 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.onloadhistory.onpushstate

    另外,您应该使用window.addEventListener('load', fn); 而不是window.onload,因为您不知道GitHub 的代码是否会覆盖window.onload

    【讨论】:

    猜你喜欢
    • 2019-03-25
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 2020-11-27
    相关资源
    最近更新 更多