使用 javascript 的后台脚本消息传递
Background script messaging with javascript
我在 Google Chrome 扩展中进行通信,并使用了以下指南:https://developer.chrome.com/extensions/messaging
它曾经有效,但我遇到了一个错误:
Error in response to tabs.query: TypeError: Cannot read property 'id'
of undefined
我比较了我的代码和 Google Chrome 代码,但我似乎无法找到为什么我的代码会产生该错误:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[1].id, {fen: request.needMove}, function(response) {
//console.log(response.farewell);
});
});
这是我发送到的地方:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log("recv FEN : " + FEN);
FEN = request.fen;
setCookie("FEN_SET", "true" , 1);
setFEN(FEN);
});
我无法修复该错误,无论我尝试什么,它都保持不变。
"Cannot read property of undefined" 暗示 'tabs' 据我所知是未定义的,但我不明白为什么它在 Google 示例中起作用,而在这里却不起作用。
另一个问题:
如果我试图将它发送到选项卡[1],这是否意味着它是第二个位置的选项卡,还是我解释错了?
tabs
是通过过滤器的所有选项卡(无论位置如何)的列表。
您的查询是 {active: true, currentWindow: true}
,因此通常它应该只有 1 个选项卡(因为最多有 1 个当前 window 且恰好有 1 个活动选项卡)。
所以你需要第一个元素,即tabs[0]
。
tabs[1]
将始终在此查询中未定义。
tabs
为空的情况过去极为罕见(Chrome 运行 在后台,没有 windows 打开)。
但是,通过最近的更改,API 将不会 return Dev Tools 选项卡。因此,如果您正在调试您的扩展程序并且 Dev Tools window 已打开并获得焦点,则该数组将为空。你应该检查一下。
我在 Google Chrome 扩展中进行通信,并使用了以下指南:https://developer.chrome.com/extensions/messaging
它曾经有效,但我遇到了一个错误:
Error in response to tabs.query: TypeError: Cannot read property 'id' of undefined
我比较了我的代码和 Google Chrome 代码,但我似乎无法找到为什么我的代码会产生该错误:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[1].id, {fen: request.needMove}, function(response) {
//console.log(response.farewell);
});
});
这是我发送到的地方:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log("recv FEN : " + FEN);
FEN = request.fen;
setCookie("FEN_SET", "true" , 1);
setFEN(FEN);
});
我无法修复该错误,无论我尝试什么,它都保持不变。 "Cannot read property of undefined" 暗示 'tabs' 据我所知是未定义的,但我不明白为什么它在 Google 示例中起作用,而在这里却不起作用。
另一个问题:
如果我试图将它发送到选项卡[1],这是否意味着它是第二个位置的选项卡,还是我解释错了?
tabs
是通过过滤器的所有选项卡(无论位置如何)的列表。
您的查询是 {active: true, currentWindow: true}
,因此通常它应该只有 1 个选项卡(因为最多有 1 个当前 window 且恰好有 1 个活动选项卡)。
所以你需要第一个元素,即tabs[0]
。
tabs[1]
将始终在此查询中未定义。
tabs
为空的情况过去极为罕见(Chrome 运行 在后台,没有 windows 打开)。
但是,通过最近的更改,API 将不会 return Dev Tools 选项卡。因此,如果您正在调试您的扩展程序并且 Dev Tools window 已打开并获得焦点,则该数组将为空。你应该检查一下。