Gmail Chrome扩展程序" chrome.extension"未定义 [英] Gmail Chrome Extension "chrome.extension" undefined

查看:132
本文介绍了Gmail Chrome扩展程序" chrome.extension"未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Gmail用户界面中运行了一个内容脚本,并在不同的点注入了一些新的HTML。这是所有工作,但为了保持代码干净,我想在一个函数调用中插入预定义的HTML标记到页面的某些部分。



这一切似乎使用chrome.extension.getURL()是可行的,但是当我测试它时,它看起来像chrome.extension是未定义的!我无法找到文档中的任何地方,说这不应该被定义和它说它应该在几个地方。



我使用chrome版本39.0.2171.95( 64位)



以下是Chrome控制台中铬对象的样子:



首先,任何人都知道为什么chrome.extension可能未定义?其次,是否有另一种(也许更好)的方式来做到这一点?我宁愿不用程序在代码中使用jQuery等代码在内容脚本中注入大量的HTML,但如果没有其他方式,可以采用这种方式。

解决方案

如果您要在控制台中测试此功能,则必须了解。



最后,出于安全原因,Chrome API的大多数都不会暴露给内容脚本。如果 API未定义,当它不应该时,您可能需要一个后台页面来为您完成这项工作。


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.

这篇关于Gmail Chrome扩展程序&quot; chrome.extension&quot;未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆