问题
I was messing around with communicating inside a Google Chrome extension and was using the following guide: https://developer.chrome.com/extensions/messaging
It used to work but I have encountered an error :
Error in response to tabs.query: TypeError: Cannot read property 'id' of undefined
I compared my code and the Google Chrome code and I can't seem to find why my code produces that error:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[1].id, {fen: request.needMove}, function(response) {
//console.log(response.farewell);
});
});
Here is where I send it to:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log("recv FEN : " + FEN);
FEN = request.fen;
setCookie("FEN_SET", "true" , 1);
setFEN(FEN);
});
I can't fix that error, whatever I try it stays the same. "Cannot read property of undefined" is implying that 'tabs' is undefined as far as I understood but I don't understand why it works in the Google example and here it doesn't.
Another Q :
If I'm trying to send it to tabs[1] does that mean it's the tab in the second position, or am I interpreting it wrong?
回答1:
tabs
is the list of all tabs (regardless of position) that pass the filter.
Your query is {active: true, currentWindow: true}
, so normally it should be just 1 tab (as there is at most 1 current window with exactly 1 active tab).
So you need the first element, which is tabs[0]
.
tabs[1]
will always be undefined with this query.
Cases when tabs
will be empty empty used to be exceedingly rare (Chrome running in background with no windows open).
However, with a recent change the API will not return the Dev Tools tab. So if you're debugging your extension and the Dev Tools window is open and focused, the array will be empty. You should check for that.
来源:https://stackoverflow.com/questions/29681477/background-script-messaging-with-javascript