【问题标题】:Javascript Not Loading in Chrome Extension ScriptJavascript 未在 Chrome 扩展脚本中加载
【发布时间】:2013-09-07 17:28:20
【问题描述】:

我要做什么

这是一个扩展,一旦页面加载,就会隐藏一个 div,其中包含一个具有“example”类的子项。

会发生什么

什么都没有。在js 页面上,我放置的任何内容都会被忽略。我已尝试使用控制台并创建页面警报,但没有任何效果。

代码

manifest.json:

{
"name": "Example",
"version": "1.0",
"default_locale": "en",
"permissions": [
    "http://example.com/*"
    ],
"content_scripts": [
    {
        "matches": [
            "http://example.com/*"
        ],
        "js": [
            "js/jquery/jquery.js",
            "src/inject/inject.js"
        ]
    }
]
}

src/inject/inject.js:

chrome.extension.sendMessage({}, function(response) {
var readyStateCheckInterval = setInterval(function() {
    if (document.readyState === "complete") {
        clearInterval(readyStateCheckInterval);

                    //Nothing here actually happens
                    alert("Extension loaded");
                    console.log("Extension loaded");

                    //The script that I *want* to happen
                    $('.example-stamp').parent().parent.().parent().hide();
    }
}, 10);
});

备注

jquery.js 文件是从jQuery.com 下载的最新文件。将解压后的扩展加载到 Chrome 中时没有错误,控制台中也没有出现任何错误,甚至没有错误。

我一直在 http://www.example.com 上测试它。

【问题讨论】:

    标签: jquery google-chrome google-chrome-extension google-chrome-app


    【解决方案1】:
    • chrome.extension.sendMessage 用于将消息从内容脚本发送到后台页面或其他扩展页面。由于您只定义了一个内容脚本,因此不会收到该消息,并且您的回调函数将永远不会被调用。
    • 通常您不需要等待文档完成状态来操作 DOM。默认情况下,Chrome 会在 document_idle 运行您的内容脚本,时间介于文档准备好和文档完成之后。见Content Scripts定义中的run_at manifest参数
    • 如果确实需要在页面加载完成后运行代码,可以将run_at设置为document_start并监听窗口加载事件。当您使用 jQuery 时,您可以这样做:
    $(window).on("load", function() {
        console.log("已加载扩展");
        $('.example-stamp').parent().parent.().parent().hide();
    });
    

    【讨论】:

    • "content_scripts": [{ "matches": [""], "js": ["content.js"], "run_at": "document_start" } 为我工作。 . 谢谢
    【解决方案2】:

    如何解决

    改变

    "content_scripts": [
        {
            "matches": [
                "http://example.com/*"
            ],
    

    "content_scripts": [
        {
            "matches": [
                "http://*.example.com/*"
            ],
    

    为什么

    答案与 js 代码无关,而是与清单有关。

    由于某种原因,除非 content-script jSON 包含字段 http://*.example.com/*,否则 javascript 不会注入,因为 http://example.com 本身无法工作,即使该 标头 URL .

    【讨论】:

      猜你喜欢
      • 2020-04-20
      • 2016-04-22
      • 1970-01-01
      • 1970-01-01
      • 2015-04-21
      • 2016-09-25
      • 2012-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多