Gmail Chrome 扩展程序“chrome.extension"不明确的 [英] Gmail Chrome Extension "chrome.extension" undefined

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

问题描述

我在 Gmail 用户界面中运行了一个内容脚本,我正在不同的点注入一些新的 HTML.这一切正常,但为了保持代码干净,我想在单个函数调用中将预定义的 HTML 标记插入页面的某些部分.

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

我使用的是 chrome 版本 39.0.2171.95(64 位)

这是 chrome 对象在 javascript 控制台中的样子:

首先,有人知道为什么 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 扩展程序“chrome.extension"不明确的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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