使用后台页面的跨域XMLHttpRequest

yuz*_*zeh 14 javascript google-chrome xmlhttprequest cross-domain google-chrome-extension

在我的Chrome扩展程序中,我想让我的options.html页面与Google的OpenId API进行通信.为了无缝地执行此操作,我iframe在选项页面上隐藏了一个弹出Google帐户登录页面(按照OpenId交互顺序等).

我的问题是我无法通过选项页面与iframe(iframe我控制的内容,但与我的chrome扩展名不同)进行通信window.postMessage.我想知道这个问题是否有快速的解决方法.

如果没有,我将options.html包含一个包含iframe页面布局和逻辑的内容.

Rob*_*b W 37

你不必搞乱iframe.可以使用后台页面执行跨域XMLHttpRequests.从Chrome 13开始,可以从内容脚本中进行跨站点请求.但是,如果页面是使用具有限制的内容安全策略标头提供的,则请求仍然可能失败connect-src.

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

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

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

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

内容脚本将通过消息传递 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*/
});
Run Code Online (Sandbox Code Playgroud)

背景/活动页面:

/**
 * 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
    }
});
Run Code Online (Sandbox Code Playgroud)

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

为了完整性,这是一个尝试我的演示的清单文件:

{
    "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
    }
}
Run Code Online (Sandbox Code Playgroud)