Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
827 views
in Technique[技术] by (71.8m points)

javascript - Why is chrome.runtime undefined?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 context scripts, or between page-level and background (spoiler, in most cases needs a context script proxy anyway).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...