Search code examples
javascriptgoogle-chrome-extensioncontent-script

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


I 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 ?


Solution

  • Content scripts run in the context of a web page and not the extension.

    Content scripts do not have access to all Chrome APIs. According to official documentation:

    Content scripts are JavaScript files that run in the context of web pages. By using the standard Document Object Model (DOM), they can read details of the web pages the browser visits, or make changes to them.

    Here are some examples of what content scripts can do:

    • Find unlinked URLs in web pages and convert them into hyperlinks
    • Increase the font size to make text more legible
    • Find and process microformat data in the DOM

    Background Script is a single long-running script to manage some task or state. While background scripts have access to all Chrome APIs.

    If you want to pass information between content scripts and background script use: Chrome Message Passing