正如 Xan 所建议的,chrome.identity API 可能是您的最佳选择。您可以获得用户的电子邮件地址并将其用作随机种子以生成您选择的代码。用户信息还包括一个“id”字段,我认为它是独一无二的,但我从未见过任何证明这一点的文档。然后,您可以使用 chrome.storage.sync API 将生成的密钥存储在您的应用程序的用户在线数据存储中。这样,用户无论何时何地登录任何设备都可以访问他们的私钥。
请注意,您必须在开发者控制台中为您的应用程序启用 oAuth2 api,并在您的应用程序清单中包含应用程序密钥和适当的范围。
这是一个粗略的例子:
function getUserInfo (interactive, callback )
{
var xmlhttp = new XMLHttpRequest();
var retry = true;
var access_token;
getToken();
/**
* Request the Auth Token
*/
function getToken()
{
chrome.identity.getAuthToken( { 'interactive': interactive }, function (token) {
if ( chrome.runtime.lastError )
{
console.log( "ERROR! " + chrome.runtime.lastError.message );
return;
}
if ( typeof token != 'undefined ')
{
access_token = token;
sendRequest( );
}
else
callback( );
});
}
function sendRequest()
{
xmlhttp.open('GET', 'https://www.googleapis.com/userinfo/v2/me' );
xmlhttp.setRequestHeader('Authorization','Bearer ' + access_token );
xmlhttp.onload = requestComplete;
xmlhttp.send();
}
function requestComplete()
{
if ( this.status == 401 && retry )
{
retry = false; // only retry once
console.log( "Request failed, retrying... " + this.response );
}
else
{
console.log( "Request completed. User Info: " + this.response );
callback(null, this.status, this.response );
var userInfo = JSON.parse( this.response );
storeUniqueKey( userInfo );
}
}
}
function storeUniqueKey( info )
{
var key;
// TODO: Generate some key using the user info: info.loginName
// user info here contains several fields you might find useful.
// There is a user "id" field here which is numeric and I believe that
// is a unique identifier that could come in handy rather than generating your
// own key.
...
chrome.storage.sync.set ( { user_key: key } );
}