How to catch events from linkedin login page buttons in pop-up in main window in angular 9

Viewed 596

I am trying to build linkedin login feature in my angular 9 application. I used angularx-social-login npm package for google and facebook login but it can't be used for linkedin.

So I am using linkedin api to for the login.

Code:-

authWindow: any;

linkedInLogin() {
    this.createOauthWindow();
}
    
createOauthWindow(width = 500, height = 600) {

    const clientId = 'my_client_id';
    const redirectUri = window.location.origin;
    const responseType = 'code';
    const scope = 'r_liteprofile';

    const url = `https://www.linkedin.com/oauth/v2/authorization?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}&response_type=${responseType}`;

    const left = (screen.width / 2) - (width / 2);
    const top = (screen.height / 2) - (height / 2);
    const options = `directories=no, titlebar=no, toolbar=no, location=no, status=no, menubar=no, scrollbars=no, resizable=no,
         copyhistory=no, width=${width},height=${height},left=${left},top=${top}`;

    this.authWindow = window.open(url, '_blank', options);

    if (window.addEventListener) {
        window.addEventListener('message', this.handleMessage, false);            
    } else {
        (window as any).attachEvent('onmessage', this.handleMessage, false);
    }
}
    
handleMessage(event) {        
    if (event.origin !== window.location.origin) {
        this.authWindow.close();
    }
    const message = event as MessageEvent;
    const result = JSON.parse(message.data);
    // code to get access token
}    

My issue is that if I click on Cancel or Sign In on the login page in the popup, all process happens in pop-up and it redirects to my site url in the pop-up.

I want to catch the events on my main window in handleMessage function if a user clicks on Cancel in pop-up or sign-in in pop-up to do further process and close the popup.

Please help, Its been a month and I am still stuck on this. I have completed this feature without using pop-up and opening the url in main window instead. But if possible I need to work with pop-up.

1 Answers

Why can't you use the official way as described here? https://www.npmjs.com/package/angularx-social-login

Subscribe to AuthState of SocialAuthService

import { SocialAuthService } from "angularx-social-login";
import { SocialUser } from "angularx-social-login";
 
@Component({
  selector: 'app-demo',
  templateUrl: './demo.component.html',
  styleUrls: ['./demo.component.css']
})
export class DemoComponent implements OnInit {
 
  user: SocialUser;
  loggedIn: boolean;
 
  constructor(private authService: SocialAuthService) { }
 
  ngOnInit() {
    this.authService.authState.subscribe((user) => {
      this.user = user;
      this.loggedIn = (user != null);
    });
  }
 
}

Code from oficial NPM package documentation

Related