问题:
您background.js
作为内容脚本注入。(Chrome 不在乎你给它起什么名字,只要你把它放在 content_scripts 的js
数组中)所以,基本上,你可以使用 jQuery 直接操作网页 DOM(就像你第一次尝试一样)——因为内容脚本可以做到这一点,但你不能使用chrome.tabs.*
(就像你的第二次尝试一样) - 因为内容脚本不能这样做。
解决方案:
由于您无法从后台页面操作网页 DOM,因此您必须通过内容脚本进行操作:
- 定义
background.js
为背景页面(或更好的事件页面)。
- 定义一个新文件(例如
content.js
作为您的内容脚本)。
- 从您的
chrome.tabs.onUpdated
侦听器(在后台页面中),使用chrome.tabs.sendMessage向相应选项卡的内容脚本发送消息。
- 在您的内容脚本中,侦听来自后台页面的消息(使用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 !");
}
});