Reputation: 2607
This issue appears frequently (but not consistently) when I try to search from the Chrome address bar. My extension sometimes does not successfully inject my custom CSS. I log both the error and the tab object for inspection, and here's what I get:
Error injecting CSS into tab (https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&es_th=1&ie=UTF-8)
Error message: No tab with id: 1202.
Tab: Object {
active: false,
height: 968,
highlighted: false,
id: 1202,
incognito: false,
index: -1,
pinned: false,
selected: false,
status: "loading",
title: "Google",
url: "https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&es_th=1&ie=UTF-8",
width: 1920,
windowId: 1203,
}
The error message claims that there is "no tab with id: (id)", but the tab object I have clearly has that ID.
First, my manifest file declares a content script I'll call "content.js" like so:
"content_scripts": [ {
"all_frames": true,
"js": [ "content.js" ],
"matches": [ "<all_urls>" ],
"match_about_blank": true,
"run_at": "document_start"
} ],
Inside the content script, I immediately send a message to a background script:
chrome.runtime.sendMessage({'init': true}, onExtensionMessage);
This background script listens for the "init" message, then executes the following function, passing it sender.tab
(where sender
is the sender of the "init" message) as its argument:
function injectTabCSS(tab) {
var url = tab.url;
chrome.tabs.insertCSS(tab.id, {
file: 'custom.css',
allFrames: true,
matchAboutBlank: true,
runAt: 'document_start'
}, function() {
if (chrome.runtime.lastError) {
console.log('Error injecting CSS into tab(', url,
')\nError message: ',
chrome.runtime.lastError.message,
'\n', tab);
}
});
}
If I (after page load) re-send the 'init' message from the content script again, the CSS is successfully inserted. This implies the issue is that the tab is in some kind of unfortunate, partially active state. It seems to me that if a tab already has a content script injected and is able to send messages to the background page, it should be able to have CSS injected also. Is this a bug, or is it expected behavior for some reason? How can I make this work more reliably?
Upvotes: 0
Views: 464
Reputation: 73846
Chrome prerenders omnibox search result pages, so when the content script is injected at "run_at": "document_start"
the tab is still hidden and its index is -1
(it's 0-based for normal tabs). Try using tabs.onReplaced event listener to process such tabs.
Upvotes: 1