下面的代码作为一个简单的测试页面,使用谷歌登录 https://developers.google.com/identity/sign-in/web/:
<html lang="en">
<head>
<script type="text/javascript">
function onGapiLoaded() {
auth = gapi.auth2.init({
client_id: "REPLACE_WITH_YOUR_ID",
scope: "profile email"
});
console.log( "signed in: " + auth.isSignedIn.get() );
auth.isSignedIn.listen( function(signedIn){ console.log( "signedin: " + signedIn ) } );
gapi.signin2.render( "signInButton", {
'width': 230,
'height': 50,
'longtitle': true,
'theme': 'dark',
'onsuccess': onSignIn
} );
}
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
console.log("Name: " + profile.getName());
};
</script>
<script src="https://apis.google.com/js/platform.js?onload=onGapiLoaded" async defer></script>
</head>
<body>
<div id="signInButton" class="g-signin2"></div>
</body>
</html>
但是如果我删除class="g-signin2"
从登录按钮,或完全删除按钮不仅按钮消失,而且整个登录库停止工作 - 我得到一个未捕获的异常:
无法读取未定义的属性“init”
当我尝试打电话时gapi.auth2.init
并且用户未登录。 auth 库似乎依赖于 dom 中存在的按钮来初始化。
我计划将其合并到我的 Angular 应用程序中,该应用程序将在任何按钮出现在舞台上之前初始化服务中的身份验证库。如果用户已经登录,则不会出现登录按钮。
根据这里的行为,如果 DOM 中没有一个按钮,我将无法使用这个库,这看起来相当有限。
为了使用.auth2
命名空间,您需要先加载它。合并它并进行一些调整,这是我推荐的代码。
<html lang="en">
<head>
<script src="https://apis.google.com/js/api.js"></script>
<script type="text/javascript">
function onSignIn(googleUser) {
console.log( "signedin");
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
console.log("Name: " + profile.getName());
};
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: "REPLACE_WITH_YOUR_ID",
scope: "profile email" // this isn't required
}).then(function(auth2) {
console.log( "signed in: " + auth2.isSignedIn.get() );
auth2.isSignedIn.listen(onSignIn);
var button = document.querySelector('#signInButton');
button.addEventListener('click', function() {
auth2.signIn();
});
});
});
</script>
</head>
<body>
<div id="signInButton"><img src="IMAGE_FILE" /></div>
</body>
</html>
有几点需要注意:
- load
api.js
代替platform.js
- 按钮资源不会自动加载,带上你的 https://developers.google.com/identity/branding-guidelines
- 如果你想利用小部件,你必须使用
platform.js
and .signin2
命名空间,但这是另一种方法,我在这里不会讨论。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)