"Cannot Read Property of Undefined" When Using Chrome.Tabs or Other Chrome API in Content Script

Cannot read property of undefined when using chrome.tabs or other chrome API in content script

As content script has its own limitations,

chrome.tabs is only available in background scripts and popup scripts.

If you wanna to use chrome.tabs then pass message from content_script to background script and play with chrome.tabs.

Cannot read property 'query' of undefined - In Vanilla Chrome Extension

The chrome.tabs API is only available in background and popup scripts. That's why it is returning tabs as undefined.

If you want to use the API, you can send a message from the content script to the background, which will use the tabs API, then send the result back to the content script.

chrome extension: Uncaught TypeError: Cannot read properties of undefined (reading 'onClicked')

Manifest v2

The following keys must be declared in the manifest to use this API.

browser_action

check this link for more details

https://developer.chrome.com/docs/extensions/reference/browserAction/

Update 1 :

Manifest v3

you need to add actions inside your manifest file

{
"action": { … }
}

and then you can call it like this

chrome.action.onClicked.addListener(tab => { … });

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

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



Related Topics



Leave a reply



Submit