1

我正在开发 Chrome 扩展程序,这是我的第一个。

一切正常,除了一部分。

我的 manifest.json 包括 background.js:

"content_scripts": [
{
  "matches": ["http://*/*","https://*/*"],
  "css": ["ui.css"],
  "js": ["jq.js","background.js"]
}
]

当我尝试像这样用 jQuery 附加 html 时:

$("body").before("<code>");

它运行完美。但是当我想这样做时:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
var pageUrl = changeInfo.url;
$.ajax({
    url: "URL",
    data: {DATA},
    datatype: "json",
    type: "POST",
    success: function(data) {
       $("body").before("<code>");
    }
 });
});

什么都没有发生..有什么想法吗?谢谢..

4

1 回答 1

3

问题:
background.js作为内容脚本注入。(Chrome 不在乎你给它起什么名字,只要你把它放在 content_scripts 的js数组中)所以,基本上,你可以使用 jQuery 直接操作网页 DOM(就像你第一次尝试一样)——因为内容脚本可以做到这一点,但你不能使用chrome.tabs.*(就像你的第二次尝试一样) - 因为内容脚本不能这样做。

解决方案: 由于您无法从后台页面操作网页 DOM,因此您必须通过内容脚本进行操作:

  1. 定义background.js为背景页面(或更好的事件页面)。
  2. 定义一个新文件(例如content.js作为您的内容脚本)。
  3. 从您的chrome.tabs.onUpdated侦听器(在后台页面中),使用chrome.tabs.sendMessage向相应选项卡的内容脚本发送消息。
  4. 在您的内容脚本中,侦听来自后台页面的消息(使用chrome.runtime.onMessage),然后执行$("body").before("<code>");

(注意:有很多替代方法,您应该选择一种更适合您的特定要求的方法。)


为了完整起见,下面是基于我上面描述的示例扩展的代码:

在 manifest.json 中:

{
    "manifest_version": 2,
    "name":    "Test Extension",
    "version": "0.0",

    "background": {
        "persistent": false,
        "scripts": ["./bg/background.js"]
    },
    "content_scripts": [{
        "matches": ["*://*/*"],
        "js":         ["./fg/content.js"],
        "run_at":     "document_start",
    }],
    "permissions": ["tabs"]
}

在 background.js 中:

chrome.tabs.onUpdated.addListener(function(tabId, info, tab) {
    console.log("One of my tabs updated: ", info);
    if (info.url) {   // <-- Not all `info` objects contain a `url` field
                      //     (Also, if a tab is refreshed, the URL is not changed,
                      //      so you will never get and `info` object with a `url` field)
        console.log("...pretending to make an AJAX request...");
        var pageURL = info.url;
        setTimeout(function() {
            // ...let's simulate an AJAX request...
            // ...now let's pretend out data arrived...
            chrome.tabs.sendMessage(tabId, {
                cmd: "doYourStuff",
                kind: "fancy"
            });
            console.log("Message sent !");
        }, 2000);
    }
});

在 content.js 中:

chrome.runtime.onMessage.addListener(function(msg) {
    console.log("Someone sent us this: ", msg);
    if (msg.cmd && (msg.cmd == "doYourStuff")) {
        alert("Watch me doing " + kind + " stuff !");
    }
});
于 2013-11-08T18:03:12.897 回答