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
236 views
in Technique[技术] by (71.8m points)

javascript - Gmail Chrome Extension "chrome.extension" undefined

I have a content script running inside the Gmail UI and I am injecting some new HTML at different points. This is all working, but to keep the code clean I wanted to insert pre-defined HTML markup into certain parts of the page in a single function call.

This all seems feasible using chrome.extension.getURL(), but when I was testing this, it looks like chrome.extension is undefined! I was unable to find anywhere in the documentation that says this shouldn't be defined and several places where it says it should.

I am using chrome Version 39.0.2171.95 (64-bit)

Here is what the chrome object looks like in the javascript console:

chrome object

First off, anyone know why chrome.extension might be undefined? Secondly, is there another (perhaps better) way to do this? I'd rather not just programmatically inject a large amount HTML into the page in code using jQuery, etc. in the content script, but can resort to this if there is no other way.

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 testing this in the console, you must be aware of the concept of the Isolated World. When you add a content script, it has a separate JavaScript context for itself that is isolated from the page.

At the top of the Console tab of Dev Tools, you'll see <top frame> in a dropdown. This is a dropdown that selects JS context it is executing in. It will list frames inside the document and all extensions that have content scripts injected.

The chrome object you show in the screenshot corresponds to what the webpage normally sees. If you switch context, you'll see a different picture:

Switching context

In any case, if you are really executing chrome.extension.getURL() in the content script - it will be well defined.


Now, if you injected a <script> tag in the page and tried it in that code - it would fail again, since the code will be in the page context. See this question for this situation.

Finally, most of the Chrome API will not be exposed to content scripts for security reasons. If an API is undefined when it shouldn't be, you may need a background page to do the job for you.


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

...