以下代码用作使用Google登录的简单测试页:
<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应用中,该应用将在舞台上出现任何按钮之前初始化服务中的auth lib。如果用户已经登录,则不会出现登录按钮。根据这里的行为,如果没有DOM中的一个看起来很狭窄的按钮,我将无法使用此lib。
为了使用.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>
有几件事要注意:
api.js
而不是platform.js
platform.js
和.signin2
命名空间,但这是我这里不讨论的另一种方法。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句