我正在尝试在我的网站上启用谷歌登录。按钮工作,与我的帐户同步,但我无法从谷歌访问userId。这就是我脑子里想的。
<script type="text/javascript">
(function() {
var po = document.createElement('script');
po.type = 'text/javascript'; po.async = true;
po.src = 'https://plus.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
</script>
这就是我试图获取用户Id的地方。在控制台中,我收到错误消息Uncaught ReferenceError: gapi is not defined.
,我以为我在上面的源代码中调用了gapi
。如有任何帮助或建议,我们将不胜感激。
$('document').ready(function(){
var request = gapi.client.plus.people.get({
'userId' : 'me'
});
request.execute(function(resp) {
console.log('ID: ' + resp.id);
console.log('Display Name: ' + resp.displayName);
console.log('Image URL: ' + resp.image.url);
console.log('Profile URL: ' + resp.url);
});
});
在加载googleapi库https://plus.google.com/js/client:plusone.js
之前,您的代码正在调用gapi.client.plus.people.get
方法。因此,你得到的漏洞不是定义错误。
工作方法-
- 为什么不起作用
我们异步调用https://plus.google.com/js/client:plusone.js
(非阻塞)以提高性能。使用异步javascript文件加载,您无法在主体加载时调用gap方法。
<script type="text/javascript">
(function() {
var po = document.createElement('script');
po.type = 'text/javascript'; po.async = true;
po.src = 'https://plus.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
</script>
- 要进行api调用,您首先必须知道javascript文件已成功加载
为此,您必须使用回调调用方法。
https://apis.google.com/js/client:plusone.js?onload=makeAPICall
编写一个api请求&在回调方法中执行它以获取数据。
检查以下示例-
<html>
<head></head>
<body>
<span id="signinButton">
<span
class="g-signin"
data-callback="signinCallback"
data-clientid="YOUR CLIENT ID.apps.googleusercontent.com"
data-cookiepolicy="single_host_origin"
data-scope="https://www.googleapis.com/auth/plus.login">
</span>
</span>
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js?onload=signinCallback';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
document.getElementById('signinButton').setAttribute('style', 'display: none');
makeAPICall();
} else {
console.log('Sign-in state: ' + authResult['error']);
}
}
function makeAPICall(){
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function (resp){
console.log(resp);
if(resp.id){
console.log('ID: ' + resp.id);
}
if(resp.displayName){
console.log('Display Name: ' + resp.displayName);
}
if(resp.image && resp.image.url){
console.log('Image URL: ' + resp.image.url);
}
if(resp.url){
console.log('Profile URL: ' + resp.url);
}
});
});
}
</script>
</body>
</html>
结论:在加载异步客户端库之前调用javascript API。
To avoid "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.". Call makeAPICall() method only when user is logged in not on every request.