Chrome扩展只运行在刷新,而不是在页面导航

Chrome extension only runs on refresh, not on page navigation

本文关键字:导航 扩展 运行 刷新 Chrome      更新时间:2023-09-26

我有一个chrome扩展,我想在GitHub上操纵一些DOM。当我刷新任何给定的页面时,所有工作都如预期的那样,但如果我导航到该页面,脚本通常不会执行。

manifest.json

{
    "manifest_version": 2,
    "name": "Name",
    "description": "Detailed description",
    "version": "1.3.5",
    "content_scripts": [{
        "matches": ["https://github.com/*/*/issues/*"],
        "js": ["jquery-2.1.0.min.js", "index.js"]
    }],
    "browser_action": {
        "default_icon": "icon.png"
    },
    "permissions": [
        "activeTab",
        "https://ajax.googleapis.com/"
    ]
}

index.js

$(document).ready(function() {
    // DOM manipulating code
    // removed for brevity
});

当你从另一个GitHub页面导航到另一个GitHub页面时,页面中的容器会更新,而不是整个页面。

所以,从我的经验来看……如果你从一个回购的主页面开始,然后切换到问题页,扩展并不总是注意到这个变化。因此,我建议将清单matches更改为所有github,而不仅仅是问题:
{
    "manifest_version": 2,
    "name": "Name",
    "description": "Detailed description",
    "version": "1.3.5",
    "content_scripts": [{
        "matches": ["https://github.com/*"],
        "js": ["jquery-2.1.0.min.js", "index.js"]
    }],
    "browser_action": {
        "default_icon": "icon.png"
    },
    "permissions": [
        "activeTab",
        "https://ajax.googleapis.com/"
    ]
}

如果这不起作用,那么在您的代码中,监视文档中的"pjax:end"事件:

document.addEventListener("pjax:end", function() {
    // run code/call function
});