chrome object or chrome.tabs object not accessible from script other than a background script

5,800 views
Skip to first unread message

riyansh karani

unread,
Sep 4, 2015, 9:16:37 AM9/4/15
to Chromium-extensions

 am experimenting with the chrome extensions API and I ran into a problem which I don't understand,

I have a background script "background.js" and a content script "content_script.js".

background.js

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript({code:"console.log('background script')"});
    chrome.tabs.executeScript({file:"javascript/content_script.js"});
});

content script

chrome.tabs.executeScript({code:"console.log('content_script')"});

The console.log in the background script works perfectly, but in the one in content_script, I get an error --> "Cannot read property 'executeScript' of undefined"

This means that I am not able to access chrome object, or the chrome.tabs object from the content script. Why is this so ?

Nick

unread,
Sep 6, 2015, 4:01:36 PM9/6/15
to Chromium-extensions
Hi Riyansh,

The reason it's returning undefined is because content scripts aren't permitted to access the chrome.tabs API. There are only a select few APIs that content scripts can access, you can view the list here. If you were looking to communicate with the background page from the content script, here's a very basic example of how to do so:

content_script.js

chrome.runtime.sendMessage({ from: 'content_script', message: 'Information from webpage.' });

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.from == 'content_script') {
    console.log('The request has been received from the content script.');
}
});

The purpose of the content script is to gather information from and manipulate aspects of a webpage (i.e. modify font size, find broken links, etc.). For this reason, as well as to provide extra functionality and maintain optimal security, they can only access the shared DOM and should never need access to the chrome.tabs API. Realistically, you would only need access to the chrome.tabs API in the context of the background/event page or popup. Hopefully this answers your question, and best of luck on your project.

Addendum: In the background page, you wouldn't need to listen for chrome.browserAction.onClicked if you've specified the popup name under "default_popup" in the manifest. Instead, listen for chrome.runtime.onMessage, as clicking on the popup will trigger runtime execution.

Sincerely,

-Nick
Reply all
Reply to author
Forward
0 new messages