javascript - 从 Firefox 扩展访问 Google Drive

标签 javascript firefox-addon google-drive-api xul

我正在尝试从 Firefox 扩展程序访问 (CRUD) Google 云端硬盘。扩展是用 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:

最佳答案

不过,根据用例,它的兴趣也可能有限。

Firefox 附带一个微型 http 服务器,只是最基本的部分。它包含用于测试目的,但这不是忽略它的理由。

让我们关注 quickstart guide for running a Drive app in Javascript

棘手的部分是设置重定向 URI 和 Javascript 来源。显然正确的设置是 http://localhost,但是您如何确定每个用户都有可用的端口 80?

你不能,除非你能控制你的用户,否则没有端口可以保证对每个人都有效。考虑到这一点,让我们选择端口 49870 并祈祷。

现在重定向 URI 和 Javascript 源设置为 http://localhost:49870

假设您使用 Add-on SDK,请将 quickstart.html(记得添加您的客户端 ID)保存在扩展的 data 目录中。现在编辑你的 main.js

const self = require("sdk/self");
const { Cc, Ci } = require("chrome");
const tabs = require("sdk/tabs");
const httpd = require("sdk/test/httpd");

var quickstart = self.data.load("quickstart.html");

var srv = new httpd.nsHttpServer();

srv.registerPathHandler("/gdrive", function handler(request, response){
  response.setHeader("Content-Type", "text/html; charset=utf-8", false);

  let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);
  converter.charset = "UTF-8";
  response.write(converter.ConvertFromUnicode(quickstart));
})

srv.start(49870);

tabs.open("http://localhost:49870/gdrive");

exports.onUnload = function (reason) {
  srv.stop(function(){});
};

请注意,quickstart.html 未作为本地文件打开,具有 resource: URI。 Drive API 不喜欢这样。它在 url http://localhost:49870/gdrive 处提供。不用说,我们可以使用模板或其他任何东西来代替静态 html。 http://localhost:49870/gdrive 也可以使用常规的 PageMod 编写脚本。

我认为这不是真正的解决方案。总比没有好。

关于javascript - 从 Firefox 扩展访问 Google Drive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25789642/

相关文章:

android - 用于 android requestSync 的 Google Drive API 始终返回 "sync request limit exceeded"

Javascript 变量就像引用而不是对象

javascript - 设置 jQuery.data() 会触发事件吗?

javascript - JS仅返回特定对象的值

javascript - 在网页中显示 Firefox 附加组件数据目录中的图像

oauth-2.0 - Dart:HttpException:无法解析 header 值

javascript - Bootstrap : change modal backdrop opacity only for specific modals

javascript - 如何在 javascript 文件中使用自定义 xml 实体

javascript - 在 firefox 插件弹出窗口中禁用任何对象的拖动

python - 使用 Drive python API 在 Google 电子表格中设置 "publish to web"