我想创建一个chrome扩展,但由于某些原因,有时chrome.runtime对象似乎不完整,并且缺少很多方法(包括onMessage ,这是我想要的)。chrome.runtime.onMessage在后台脚本中未定义(chrome扩展名)
它有时似乎有效,有时不起作用。我认为这可能是一个时间相关的问题,但我不明白为什么我不能简单地在后台创建一个消息监听器?
我的背景脚本:
setTimeout(function() {
console.log("gogo!");
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.type == "tab") {
console.log("tab!");
sendResponse({status: "ok"});
}
}),
2
});
其中 “chrome.runtime.onMessage” 是不确定的。
谢谢!编辑2:我已经构建了一个更简单的原型,它又失败了。现在我真的很困惑。以下是我有:
$tree
.
├── manifest.json
├── src
│ ├── background.html
│ ├── background.js
│ └── test.js
└── vendor
└── jquery.js
2 directories, 5 files
manifest.json档案:
{
"manifest_version": 2,
"name": "test",
"description": "test",
"version": "1.0",
"author": "test",
"homepage_url": "http://www.test.com",
"content_scripts": [
{
"run_at" : "document_idle",
"matches": ["https://www.google*"],
"js": ["vendor/jquery.js", "src/test.js"]
}
],
"background": {
"page": "src/background.html",
"persistent": false
},
"permissions": [
"tabs",
"https://www.google*"
]
}
background.html文件:
<script src="../vendor/jquery.js"></script>
<script src="background.js"></script>
background.js文件:
function run() {
console.log("gogo!");
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.type == "tab") {
console.log("tab!");
sendResponse({status: "ok"});
}
});
}
run();
测试.js文件:
'use strict';
run();
function run() {
var url = window.location.href;
// Error if no URI
if (!url) {
return 1;
}
var uriRe = /https:\/\/www\.google.*/;
var reParse = uriRe.exec(url);
if (!reParse) {
return 2;
}
chrome.runtime.sendMessage({type: "tab"}, function(response) {
console.log(response);
});
}
我在OSX上使用Chrome 49.0.2623.112(64位)。
编辑:这是发生了什么失败的时间截图:(?也许50%的时间)
我想再次精确,它并没有失败所有的时间,这使得它变得更加奇怪,并且让我相信在某种我不知道的地方存在一种“种族”状况。
你为什么在超时包装呢? –
您的背景页面是活动页面吗? (“persistent”:false set)如果是这样,你不应该调用setTimeout。如果是事件页面,请查看[docs](https://developer.chrome.com/extensions/event_pages),因为有些事情需要注意。 –
@DanielHerr这只是一个测试,因为我怀疑与时间有关的问题。看起来它在超时时间表现更好,但我不确定。 – tbronchain