Search code examples
javascriptangulargoogle-chromeoauthgoogle-oauth

How to automate button click in angular 4 app?


Want to execute code inside this.auth2.attachClickHandler without the button click.
Not able to figure out

Requirement
Want to go for google authorization when the page renders without having to click any button.
Code is working and fetching me the google auth token when I click google sign in button.
But how to execute it without clicking the button.

CODE

import { Component, ElementRef, AfterViewInit } from '@angular/core';
declare const gapi: any;

@Component({
  selector: 'google-signin',
  template: '<button id="googleBtn">Google Sign-In</button>'
})
export class GoogleSigninComponent implements AfterViewInit {

  private clientId: string = 'XXXXXX';

  private scope = [
    'profile',
    'email',
    'https://www.googleapis.com/auth/plus.me',
    'https://www.googleapis.com/auth/contacts.readonly',
    'https://www.googleapis.com/auth/admin.directory.user.readonly'
  ].join(' ');

  public auth2: any;

  ngOnInit() {
    //this.googleInit();
  }

  public googleInit() {
    let that = this;
    gapi.load('auth2', function () {
      that.auth2 = gapi.auth2.init({
        client_id: that.clientId,
        cookiepolicy: 'single_host_origin',
        scope: that.scope
      });
      that.attachSignin(that.element.nativeElement.firstChild);
    });
  }
  public attachSignin(element) {
    let that = this;
    console.log(this.auth2);
    let x = document.querySelector('#googleBtn')//.click();
    console.log(x);
    //Execute code inside this attachClickHandler automatically
    this.auth2.attachClickHandler(element, {},
      function (googleUser) {
        console.log(googleUser);
        let profile = googleUser.getBasicProfile();
        console.log('Token || ' + googleUser.getAuthResponse().id_token);
        console.log('ID: ' + profile.getId());
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail());
      }, function (error) {
        console.log(JSON.stringify(error, undefined, 2));
      });
  }

  constructor(private element: ElementRef) {
    //console.log('ElementRef: ', this.element);
  }

  ngAfterViewInit() {
    this.googleInit();

  }

}

Can anybody guide me on this?I am still learning. Thanks


Solution

  • when you reach that page, you can keep a query parameter in the url like ?google=true and in the ngAfterViewInit you could check if the query parameter is set, if yes then you could call the google auth otherwise dont

    For more understanding on accessing query params

    https://www.tektutorialshub.com/angular-passing-optional-query-parameters-to-route/