3
The problem:
You are injecting background.js as a content script. (Chrome does not care what you name it, just that you put it in content_scripts's js array) So, basicaly, you can use jQuery to directly manipulate a web-pages DOM (like in your first attempt) - because content scripts can do that, but you cannot use chrome.tabs.* (like in your second attempt) - because content scripts cannot do that.
问题是:你在注射背景。作为内容脚本的js。(Chrome不关心你的名字,只是你把它放在content_scripts的js数组中)所以,basicaly,你可以使用jQuery直接操作一个网页DOM(就像你的第一次尝试一样)——因为内容脚本可以做到这一点,但是你不能使用chrome.tab。*(就像第二次尝试一样)——因为内容脚本不能做到这一点。
The solution: Since you cannot manipulate a web-pages DOM from a background page, you have to do it through a content script:
解决方案:由于无法从后台页面操作web页面DOM,所以必须通过内容脚本:
Define background.js as a background page (or better yet
定义背景。js作为后台页面(或更好的事件页面)。
Define a new file (e.g. content.js as your content script).
定义一个新文件(例如内容)。作为你的内容脚本)。
From your chrome.tabs.onUpdated listener (in the background page), send a message to the corresponding tab's content script, using
从你的chrome.tabs。onupdate listener(在后台页面),使用chrome.tabs.sendMessage向相应的选项卡的内容脚本发送一条消息。
In your content script, listen for messages from the background page (using $("body").before("");
在内容脚本中,从背景页面(使用chrome.runtime.onMessage)侦听消息,然后执行$(“body”)。
(Note: There plenty of alternative approaches and you should pick one that better fits your specific requirements.)
(注意:有很多可供选择的方法,您应该选择一种更适合您的特定需求的方法。)
For the sake of completeness, below is a code of a sample extension, based on what I described above:
为了完整性起见,下面是基于我上面描述的示例扩展代码:
In manifest.json:
在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"]
}
In background.js:
在background.js:
chrome.tabs.onUpdated.addListener(function(tabId, info, tab) {
console.log("One of my tabs updated: ", info);
if (info.url) { //
// (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);
}
});
In content.js:
在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 !");
}
});