0

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 ?

Maverick
  • 1,519
  • 18
  • 32
ironstein
  • 421
  • 5
  • 16
  • 2
    covered in the official docs regarding content scripts. – Zig Mandel Sep 04 '15 at 13:04
  • 1
    @ZigMandel can you send me a link please. Could not find it. – ironstein Sep 04 '15 at 13:05
  • its in the very first page of contents scripts, plus its a duplicate question. Do spend more effort investigating. – Zig Mandel Sep 04 '15 at 14:14
  • 1
    @ZigMandel you could have told me that in the last question, instead of making me take the longer route only to object. – ironstein Sep 04 '15 at 17:40
  • 1
    no, its fine to post a question but following the guidelines (see if an answer exists, consult offcial docs etc). what i meant is you cant keep asking different questions in the comments of an answer for something else. in the end it seems you got the answer you were looking for anyways (by linking here to the dup) – Zig Mandel Sep 04 '15 at 17:47
  • The manifest will need the activeTab permission to allow the extension temporary access to the current page, and the scripting permission to use the Scripting API's executeScript method. { "name": "Getting Started Example", ... "permissions": ["storage", "activeTab", "scripting"], ... } – hadialaoui Jan 31 '21 at 21:38

1 Answers1

8

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