Why chrome.runtime undefined?

I am creating a Google Chrome extension (my first) and I want to send messages from the extension to the current tab.

I follow the documentation:

https://developer.chrome.com/apps/runtime#event-onMessage

The extension loads a small external JS into the HTML code of the tab, which contains the following code:

chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { console.log(request) } ); 

As soon as JS loads, I get the following error:

Uncaught TypeError: Cannot read property 'onMessage' of undefined .

Open the console and type chrome , I see that the runtime is not a chrome property.

It sounds like I'm doing something wrong, but what? Do I need to add something to the manifest.json file?

Chrome version 39.0.2171.71 m

Thanks.

+2
javascript google-chrome-extension
source share
2 answers

If you embed JavaScript in a page with a <script> , it runs in the context of the page.

Sometimes desirable : this is the only way to access page-level JavaScript objects.

But in your case, this means that the code does not have access to the Chrome API, since it is "the same" as the page code.

You need to study the relationship between pages and contextual scripts or between page level and background (spoiler, in most cases, in any case, you need a script context proxy).

+7
source share

or it could just be a heisenbag that only appears under certain circumstances. in my case, closing the chrome: // extensions tab and updating my goal made chrome.runtime again available. Why is chrome.runtime not defined in the content script?

0
source share

All Articles