11

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

I am following the documentation:

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

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

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

As soon as the JS is loaded I get the following error:

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

Opening console and typing chrome, I can see that the runtime is not a property of chrome.

It looks like I am doing something wrong, but what? Do I need to add something to the manifest.json file?

Chrome Version 39.0.2171.71 m

Thank you.

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
igasparetto
  • 1,086
  • 1
  • 12
  • 28

2 Answers2

12

If you're inserting JavaScript into a page with a <script> tag, it executes in the page's context.

Sometimes it is desirable: that's the only way to access page-level JavaScript objects.

But in your case it means that the code does not have access to Chrome APIs, as it is "the same" as the page's code.

You need to look into communicating between page-level and content scripts, or between page-level and background (spoiler, in most cases needs a context script proxy anyway).

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
Xan
  • 74,770
  • 16
  • 179
  • 206
  • I'm extremely stumped on this. I have a chrome extension with 5K users that works 99% of the time. The other 1% of the time there are errors saying that chrome.runtime is undefined. I can't figure out how chrome.runtime could possibly be undefined sometimes. I'd love any guidance you could provide on this. mike at scribbl.co (would really appreciate some help here) – Mike Sallese Aug 25 '22 at 21:07
9

or it could just be a Heisenbug which only appears under certain circumstances. in my case, closing the chrome://extensions tab and refreshing my target caused chrome.runtime to be available again. Why is chrome.runtime undefined in the content script?

jcomeau_ictx
  • 37,688
  • 6
  • 92
  • 107