This is a known feature of Chrome Extensions called isolated world. Content scripts are injected into a target page and can not be accessed from other parts of the extension directly. To interact you should use messaging.
Here is a bit outdated SO answer to a related question which may be helpful to make a whole picture. In the answer you should adapt the code to work with sendMessage
instead of sendRequest
, which was removed in favor of the first one.
For example, you place in the background page the following call (taken from the documentation):
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, // you can send "DoSomething" for example
function(response) {
console.log(response.farewell);
});
});
In the content script you should listen to the message:
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if(request.greeting == "hello")
sendResponse({farewell: "goodbye"});
// else if(request.greeting == "DoSomething") DoSomething();
});
I don't think getViews
method is what you want, because it returns your extension pages (background, popups, options), and not the pages where your content scripts are injected. I suppose you should either sendMessage
s from your content script to the background page, so that the later "knows" all scripts host pages, or you can use executeScript
.
chrome.tabs.executeScript(tabId, {code: 'DOsomething();'})