Creating a Login Button
The following code is the HTML we need to set up the sign-in button. There are about a dozen attributes you can set on the button, but for brevity, we’ll only talk about the few that are the most important.
<span id="signinButton" class="offset6"> <span class="g-signin" data-callback="signinCallback" data-clientid="<CLIENT ID>" data-cookiepolicy="single_host_origin" data-requestvisibleactions="http://schemas.google.com/WantActivity" data-scope="https://http://www.googleapis.com/auth/plus.login"> </span> </span>
data-callback specifies the JavaScript function that will receive the result of client login. data-clientid is the client ID value preceding .apps.googleusercontent.com in the API console.
data-cookiepolicy directs Google+ to use a session cookie and HTML5 session storage for the user on the client. If a user is logged in to multiple Google+ accounts, the cookiepolicy will allow the website to give the user a choice of which account to use to authenticate. On pages with a sign-in button, the client-side data can discern if the user is logged in, reducing button loading and latency issues. single_host_origin is an alias for specifying that you have no subdomains that will access the cookie, and while it is appropriate for testing, you should specify a uniform resource identifier (URI) in production, as it gives you the flexibility to restrict the scheme, domain, and port. For example, you might want all calls to use SSL. There is also a fallback policy option, none. It prevents cookies or session storage being used, but may present problems if the user is logged in to multiple accounts at the same time.
data-requestvisibleactions specifies the actions this application can do on behalf of the user. We’ll be talking about it more in the next section.
Our callback attempts to load the user’s profile data if the login was successful.
function signinCallback(result) { if (result['access_token']) { document.querySelector('#signinButton').setAttribute('style', 'display:none'); loadProfileInfo(); } else if (result['error']) { console.log(result); } }
Near the bottom of your page, add the following snippet of code that dynamically loads the button.
<script type="text/javascript"> (function () { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'http://apis.google.com/js/client:plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script>
If the styling of the preset button doesn’t suit you, you can customize it. However, you must comply with Google’s branding guidelines.