在我的 Chrome 扩展程序中,我想让我的 options.html
页面与 Google 的 OpenId API 之类的东西进行通信。为了无缝地完成此操作,我在选项页面上有一个隐藏的 iframe
,它将弹出 Google 帐户登录页面(遵循 OpenId 交互序列等)。
我的问题是我无法从选项页面到 iframe 进行通信(iframe 的来源是我控制的,但与我的 chrome 扩展不同)通过window.postMessage
。我想知道是否有快速解决此问题的方法。
如果没有,我将使 options.html
包含一个 iframe
来容纳页面的布局和逻辑。
In my Chrome extension, I want to have my options.html
page communicate with something like Google's OpenId API. In order to do this seamlessly, I have a hidden iframe
on the options page which will pop-up the Google Accounts login page (following the OpenId interaction sequence, etc.).
My issue is that I can't communicate from the options page to the iframe
(the origin of the iframe
is something I control, but not the same as my chrome extension) via window.postMessage
. I was wondering if there is a quick workaround to this issue.
If there isn't, I'm going to make options.html
contain an iframe
that houses the layout and logic of the page.
发布评论
评论(2)
您不必搞乱 iframe。使用后台页面可以执行跨域 XMLHttpRequest。从 Chrome 13 开始,可以从内容脚本发出跨站点请求。但是,如果页面提供的内容安全策略标头具有限制性
connect-src
。选择 nexy 方法而不是内容脚本的另一个原因是,对 http 站点的请求将导致混合内容警告(“https:// 的页面...显示来自 http://...的不安全内容”)。
将请求委托给后台页面的另一个原因是当您想要从
file://
获取资源时,因为内容脚本无法从file:
读取,除非它在 file://
方案的页面上运行。使用后台脚本的跨站点请求。
内容脚本将通过 messaging API 从后台请求功能。这是发送和获取请求响应的非常简单方法的示例。
背景 / 活动页面:
备注:消息API已被重命名多次。如果您的目标浏览器不是最新的 Chrome 版本,请查看此答案。
为了完整起见,这里有一个 manifest 文件来试用我的演示:
You don't have to mess with iframes. It's possible to perform cross-domain XMLHttpRequests, using background pages. Since Chrome 13, cross-site requests can be made from the content script. However, requests can still fail if the page is served with a Content Security Policy header with a restricting
connect-src
.Another reason for choosing the nexy method over content scripts is that requests to http sites will cause a mixed content warning ("The page at https://... displayed insecure content from http://...").
Yet another reason for delegating the request to the background page is when you want to get a resource from the
file://
, because a content script cannot read fromfile:
, unless it is running on a page at thefile://
scheme.Cross-site request using background script.
The content script would request the functionality from the background via the messaging API. Here is an example of a very simple way of sending and getting the response of a request.
Background / event page:
Remark: The messaging APIs have been renamed several times. If your target browser is not the latest Chrome version, check out this answer.
For completeness, here's a manifest file to try out my demo:
我使用 jquery 实现了同样的事情,它更简单,而且效果也很好。background.js
但
contentscript.js
请确保 manifest.json 文件具有所需的权限和 jquery js 文件
I implemented the same thing using jquery its much simpler and it worked great too..
background.js
contentscript.js
But make sure manifest.json file has required permissions and jquery js file