Search code examples
javascriptgoogle-oauthgoogle-calendar-api

Initiate Javascript Google Sign-In without a Sign-In button, on page load?


Here is a working code for pulling Google Calendar events. To sign-in you click SignIn button. You get Google authorization screen, when Google API pulls calendar events and displays them in a list.

Question: I don't want any Sign In buttons, I want sign in to be triggered on page load. Here is the code. It should be some small change. Please let me know if you know how to do this. Thanks.

<!DOCTYPE html>
<html>

<head>
  <title>Google Calendar Events</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>

<body>
  <div class="container">
    <div class="row">
      <h1>Google Calendar Events</h1>
      <button id="signinButton">Sign In</button>
      <button id="signoutButton">Sign Out</button>
      <br>
      <br>
      <div id="eventContainer"></div>
    </div>
  </div>
  <!-- Include the Google API library -->
  <script src="https://apis.google.com/js/api.js"></script>
  <script>
    // Client ID and API key from the Google API Console
    var CLIENT_ID = 'YOUR_CLIENT_ID';
    var API_KEY = 'YOUR_API_KEY';

    // Array of API discovery doc URLs for APIs used
    var DISCOVERY_DOCS = ['https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest'];

    // Authorization scopes required by the API
    var SCOPES = 'https://www.googleapis.com/auth/calendar.readonly';

    var signinButton = document.getElementById('signinButton');
    var signoutButton = document.getElementById('signoutButton');
    var eventContainer = document.getElementById('eventContainer');

    // Load the API client and authenticate the user
    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 () {
        // Listen for sign-in state changes
        gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

        // Handle the initial sign-in state
        updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());

        signinButton.onclick = handleSigninClick;
        signoutButton.onclick = handleSignoutClick;
      });
    }

    function updateSigninStatus(isSignedIn) {
      if (isSignedIn) {
        signinButton.style.display = 'none';
        signoutButton.style.display = 'block';
        listUpcomingEvents();
      } else {
        signinButton.style.display = 'block';
        signoutButton.style.display = 'none';
        eventContainer.innerHTML = '';
      }
    }

    function handleSigninClick() {
      gapi.auth2.getAuthInstance().signIn();
    }

    function handleSignoutClick() {
      gapi.auth2.getAuthInstance().signOut();
    }

    // Retrieve and display the upcoming calendar events
    function listUpcomingEvents() {
      gapi.client.calendar.events.list({
        'calendarId': 'primary',
        'timeMin': (new Date()).toISOString(),
        'showDeleted': false,
        'singleEvents': true,
        'maxResults': 10,
        'orderBy': 'startTime'
      }).then(function (response) {
        var events = response.result.items;
        var eventList = document.createElement('ul');
        eventList.className = 'list-group';

        if (events.length > 0) {
          for (var i = 0; i < events.length; i++) {
            var event = events[i];
            var eventItem = document.createElement('li');
            eventItem.className = 'list-group-item';
            eventItem.appendChild(document.createTextNode(event.summary));
            eventList.appendChild(eventItem);
          }
          eventContainer.appendChild(eventList);
        } else {
          eventList.appendChild(document.createTextNode('No upcoming events found.'));
        }
      });
    }
  </script>
  <script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
</body>

</html>

Solution

  • you have to use the Google Sign-In API here is the example :-

    //put at head of the docs
    <script src="https://apis.google.com/js/platform.js" async defer></script>
    

    put this into your JS file

    // This function is called when the Google Sign-In API library is loaded
    function handleClientLoad() {
      // Initialize the API with your client ID
      gapi.load('auth2', function() {
        gapi.auth2.init({
          client_id: 'YOUR_CLIENT_ID',
        });
        // Call the sign-in method after initialization
        gapi.auth2.getAuthInstance().signIn();
      });
    }
    

    now to trigger the initialization on page load

    <body onload="handleClientLoad()">