我有一个initClient()函数,当我在页面上有class ='g-signin2'按钮时,该函数无法触发。我认为我的错误是在单个页面上混合了两种不同的Google身份验证方法。但是我不确定如何使用g-signin2按钮正确初始化gapi.client。
页面为:
<!DOCTYPE html>
<html>
<head>
<meta name="google-signin-scope" content="profile email drive" />
<meta name="google-signin-client_id" content="[...].apps.googleusercontent.com">
<script async defer src="https://apis.google.com/js/platform.js?onload=handleClientLoad"></script>
<script type="text/javascript">
var CLIENT_ID = '[...].apps.googleusercontent.com';
var API_KEY = '[...]';
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"];
var SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly';
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
console.log("one of those sign-in state changes");
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
}, function(error) {
appendPre(JSON.stringify(error, null, 2));
});
}
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
listFiles();
}
}
function listFiles() {
gapi.client.drive.files.list({
'pageSize': 10,
'fields': "nextPageToken, files(id, name)"
}).then(function(response) {
console.log(response.result.files);
});
}
function onSignIn(googleUser) {
console.log("Logged in as: " + googleUser.getBasicProfile().getEmail());
}
</script>
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
</body>
</html>
只需从按钮中删除'g-siginin2'类,即可使initClient执行和运行listFiles(),但我依靠'g-signin2'按钮来触发onSignIn的其他功能。按原样使用该代码,initClient将永远不会运行。
正确的方法是什么?