Google API客户端与Google Chrome扩展程序的兼容性

时间:2014-01-08 17:56:28

标签: api google-chrome google-chrome-extension

我正在使用Google Chrome扩展程序,我想使用Google的客户端API https://apis.google.com/js/client.js来检索用户的Google+ ID。

我在manifest.json中提供了以下值:

"oauth2": {
    "client_id": "[CLIENT ID].apps.googleusercontent.com",
    "scopes": [
        "https://www.googleapis.com/auth/plus.login",
        "https://www.googleapis.com/auth/plus.me"
    ]
}

提供这些值可让我成功调用chrome.identity.getAuthToken:http://developer.chrome.com/apps/identity.html

getAuthToken: function () {
    chrome.identity.getAuthToken({
        interactive: false
    }, function (authToken) {

        if (chrome.runtime.lastError) {
            //  User isn't signed into Google Chrome.
            console.error(chrome.runtime.lastError.message);
        }
    });
}

一旦我有一个身份验证令牌,我就能发出一个AJAX请求并成功获取我的信息:

$.ajax({
    url: 'https://www.googleapis.com/plus/v1/people/me',
    headers: {
        'Authorization': 'Bearer ' + authToken
    },
    success: function (response) {
        console.log("Received user info", response);
    },
    error: function (error) {
        console.error(error);
    }
});

但这些都不使用上述的Google客户端API。相反,利用它会很好,但我想知道它是否不适用于谷歌Chrome扩展。我能够至少让事情像这样工作:

GoogleAPI.auth.authorize({
    client_id: '[CLIENT ID].apps.googleusercontent.com',
    scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.me',
    //  Set immediate to false if authResult returns null
    immediate: true
}, function(){
    GoogleAPI.client.load('plus', 'v1', function () {

     var request = GoogleAPI.client.plus.people.get({
        'userId': 'me'
     });

     request.execute(function (response) {
        console.log("Response:", response);
     });
});

但是我已经在我的清单中指定了这些值 - 所以重新引用它们似乎有点奇怪。我可以加载我的清单并解析它,但我已经在上面成功地工作了。

此外,您必须调用GoogleAPI.client.setApiKey才能使用Google的内容。这适用于开发环境,因为我能够将机器的IP列入白名单,但这在生产环境中不起作用,因为会有许多客户端连接。

那么,Google的客户端API是否应该在Google Chrome扩展程序中使用?

0 个答案:

没有答案
相关问题