【发布时间】:2014-09-11 14:07:43
【问题描述】:
我正在尝试从 Firefox 扩展程序访问 (CRUD) Google Drive。扩展是用 Javascript 编码的,但现有的两个 javascript SDK 似乎都不适合;客户端 SDK 期望“窗口”可用,而扩展中不是这种情况,并且服务器端 SDK 似乎依赖于特定于节点的设施,因为在节点中工作的脚本在我加载时不再执行通过browserify运行它后它在chrome中。我是否卡在使用原始 REST 调用? 运行的 Node 脚本如下所示:
var google = require('googleapis');
var readlineSync = require('readline-sync');
var CLIENT_ID = '....',
CLIENT_SECRET = '....',
REDIRECT_URL = 'urn:ietf:wg:oauth:2.0:oob',
SCOPE = 'https://www.googleapis.com/auth/drive.file';
var oauth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
var url = oauth2Client.generateAuthUrl({
access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
scope: SCOPE // If you only need one scope you can pass it as string
});
var code = readlineSync.question('Auth code? :');
oauth2Client.getToken(code, function(err, tokens) {
console.log('authenticated?');
// Now tokens contains an access_token and an optional refresh_token. Save them.
if(!err) {
console.log('authenticated');
oauth2Client.setCredentials(tokens);
} else {
console.log('not authenticated');
}
});
我在这个脚本上使用 browserify 包装了节点 GDrive SDK:
var Google = new function(){
this.api = require('googleapis');
this.clientID = '....';
this.clientSecret = '....';
this.redirectURL = 'urn:ietf:wg:oauth:2.0:oob';
this.scope = 'https://www.googleapis.com/auth/drive.file';
this.client = new this.api.auth.OAuth2(this.clientID, this.clientSecret, this.redirectURL);
}
}
然后在单击按钮后调用它(如果文本字段没有代码,它会启动浏览器来获取):
function authorize() {
var code = document.getElementById("code").value.trim();
if (code === '') {
var url = Google.client.generateAuthUrl({access_type: 'offline', scope: Google.scope});
var win = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow('navigator:browser');
win.gBrowser.selectedTab = win.gBrowser.addTab(url);
} else {
Google.client.getToken(code, function(err, tokens) {
if(!err) {
Google.client.setCredentials(tokens);
// store token
alert('Succesfully authorized');
} else {
alert('Not authorized: ' + err); // always ends here
}
});
}
}
但这会产生错误Not authorized: Invalid protocol: https:
【问题讨论】:
-
@friflaj 您是否尝试模仿窗口 obj ?
window = Window = {}形成一个高层次,看起来他们只使用 winodw obj 来存储全局变量 -
这就是我现在正在尝试的。 Node 版本使用一种动态模块加载的形式,似乎可以避开 browserify,所以我已经放弃了。
-
您是否尝试过使用 iFrame?我相信在 Firefox 中您可以访问“背景脚本”。这基本上是您的代码在其上执行的无头 html 页面。您应该能够在此处生成 iFrame。 (只是吐口水,我以前做过这个工作,但不记得是怎么做到的)
-
我想知道这是否有帮助:stackoverflow.com/questions/8915087/…
-
我只是想添加一个警告,您不应该尝试完全在客户端执行此操作,因为这将涉及(如您在上面发布的)在您的源代码中公开您的客户端密码附加组件(可通过文件系统访问)。这会给附加组件的用户带来安全风险。相反,我会在您的插件可以调用的单独服务器上托管一个小型应用程序,该应用程序将使用标准 OAuth 方法(回调 URL 等)对用户进行身份验证。
标签: javascript firefox-addon google-drive-api xul