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:
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.
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: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.