使用后台页面的跨域XMLHttpRequest

发布于 2024-12-09 00:13:12 字数 374 浏览 0 评论 0 原文

在我的 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

∞觅青森が 2024-12-16 00:13:12

您不必搞乱 iframe。使用后台页面可以执行跨域 XMLHttpRequest。从 Chrome 13 开始,可以从内容脚本发出跨站点请求。但是,如果页面提供的内容安全策略标头具有限制性connect-src

选择 nexy 方法而不是内容脚本的另一个原因是,对 http 站点的请求将导致混合内容警告(“https:// 的页面...显示来自 http://...的不安全内容”)。

将请求委托给后台页面的另一个原因是当您想要从 file:// 获取资源时,因为内容脚本无法从 file: 读取,除非它在 ​​file:// 方案的页面上运行。

注意
要启用跨源请求,您必须使用清单文件中的 permissions 数组显式向您的扩展程序授予权限。

使用后台脚本的跨站点请求。

内容脚本将通过 messaging API 从后台请求功能。这是发送和获取请求响应的非常简单方法的示例。

chrome.runtime.sendMessage({
    method: 'POST',
    action: 'xhttp',
    url: 'http://www.stackoverflow.com/search',
    data: 'q=something'
}, function(responseText) {
    alert(responseText);
    /*Callback function to deal with the response*/
});

背景 / 活动页面:

/**
 * Possible parameters for request:
 *  action: "xhttp" for a cross-origin HTTP request
 *  method: Default "GET"
 *  url   : required, but not validated
 *  data  : data to send in a POST request
 *
 * The callback function is called upon completion of the request */
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
    if (request.action == "xhttp") {
        var xhttp = new XMLHttpRequest();
        var method = request.method ? request.method.toUpperCase() : 'GET';

        xhttp.onload = function() {
            callback(xhttp.responseText);
        };
        xhttp.onerror = function() {
            // Do whatever you want on error. Don't forget to invoke the
            // callback to clean up the communication port.
            callback();
        };
        xhttp.open(method, request.url, true);
        if (method == 'POST') {
            xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        }
        xhttp.send(request.data);
        return true; // prevents the callback from being called too early on return
    }
});

备注:消息API已被重命名多次。如果您的目标浏览器不是最新的 Chrome 版本,请查看此答案

为了完整起见,这里有一个 manifest 文件来试用我的演示:

{
    "name": "X-domain test",
    "manifest_version": 2,
    "permissions": [
        "http://www.stackoverflow.com/search*"
    ],
    "content_scripts": {
        "js": ["contentscript.js"],
        "matches": ["http://www.example.com/*"]
    },
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    }
}

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 from file:, unless it is running on a page at the file:// scheme.

Note
To enable cross-origin requests, you have to explicitly grant permissions to your extension using the permissions array in your manifest file.

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.

chrome.runtime.sendMessage({
    method: 'POST',
    action: 'xhttp',
    url: 'http://www.stackoverflow.com/search',
    data: 'q=something'
}, function(responseText) {
    alert(responseText);
    /*Callback function to deal with the response*/
});

Background / event page:

/**
 * Possible parameters for request:
 *  action: "xhttp" for a cross-origin HTTP request
 *  method: Default "GET"
 *  url   : required, but not validated
 *  data  : data to send in a POST request
 *
 * The callback function is called upon completion of the request */
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
    if (request.action == "xhttp") {
        var xhttp = new XMLHttpRequest();
        var method = request.method ? request.method.toUpperCase() : 'GET';

        xhttp.onload = function() {
            callback(xhttp.responseText);
        };
        xhttp.onerror = function() {
            // Do whatever you want on error. Don't forget to invoke the
            // callback to clean up the communication port.
            callback();
        };
        xhttp.open(method, request.url, true);
        if (method == 'POST') {
            xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        }
        xhttp.send(request.data);
        return true; // prevents the callback from being called too early on return
    }
});

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:

{
    "name": "X-domain test",
    "manifest_version": 2,
    "permissions": [
        "http://www.stackoverflow.com/search*"
    ],
    "content_scripts": {
        "js": ["contentscript.js"],
        "matches": ["http://www.example.com/*"]
    },
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    }
}
一指流沙 2024-12-16 00:13:12

我使用 jquery 实现了同样的事情,它更简单,而且效果也很好。background.js

chrome.runtime.onMessage.addListener(function(request, sender, callback) {
  if (request.action == "xhttp") {

    $.ajax({
        type: request.method,
        url: request.url,
        data: request.data,
        success: function(responseText){
            callback(responseText);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            //if required, do some error handling
            callback();
        }
    });

    return true; // prevents the callback from being called too early on return
  }
});

contentscript.js

chrome.runtime.sendMessage({
        method: 'POST',
        action: 'xhttp',
        url: 'http://example-url.com/page.php',
        data: "key=value"
    }, function(reponseText) {
        alert(responseText);
    }); 

请确保 manifest.json 文件具有所需的权限和 jquery js 文件

  "permissions": [
      "tabs", "activeTab", "http://example-url.com/*"
  ],
  "content_scripts": [ {
      "js": [ "jquery-3.1.0.min.js", "contentscript.js" ],
      "matches": [ "https://example-ssl-site.com/*" ]
  }],
  "background": {
      "scripts": [ "jquery-3.1.0.min.js", "background.js" ]
  }

I implemented the same thing using jquery its much simpler and it worked great too..

background.js

chrome.runtime.onMessage.addListener(function(request, sender, callback) {
  if (request.action == "xhttp") {

    $.ajax({
        type: request.method,
        url: request.url,
        data: request.data,
        success: function(responseText){
            callback(responseText);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            //if required, do some error handling
            callback();
        }
    });

    return true; // prevents the callback from being called too early on return
  }
});

contentscript.js

chrome.runtime.sendMessage({
        method: 'POST',
        action: 'xhttp',
        url: 'http://example-url.com/page.php',
        data: "key=value"
    }, function(reponseText) {
        alert(responseText);
    }); 

But make sure manifest.json file has required permissions and jquery js file

  "permissions": [
      "tabs", "activeTab", "http://example-url.com/*"
  ],
  "content_scripts": [ {
      "js": [ "jquery-3.1.0.min.js", "contentscript.js" ],
      "matches": [ "https://example-ssl-site.com/*" ]
  }],
  "background": {
      "scripts": [ "jquery-3.1.0.min.js", "background.js" ]
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文