如何在angular 9的主窗口中的弹出窗口中捕获来自linkedin登录页面按钮的事件

aja*_*ain 6 addeventlistener oauth-2.0 linkedin-api angular

我正在尝试在我的 angular 9 应用程序中构建linkedin 登录功能。我将angularx-social-login npm 包用于 google 和 facebook 登录,但它不能用于linkedin。

所以我使用linkedin api来登录。

代码:-

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
}    
Run Code Online (Sandbox Code Playgroud)

我的问题是,如果我在弹出窗口的登录页面上单击取消或登录,所有过程都在弹出窗口中发生,并在弹出窗口中重定向到我的网站 url。

如果用户单击弹出窗口中的取消或登录弹出窗口以执行进一步处理并关闭弹出窗口,我想在handleMessage函数中捕获主窗口上的事件。

请帮忙,已经一个月了,我仍然坚持这个。我已经完成了这个功能,没有使用弹出窗口,而是在主窗口中打开 url。但如果可能的话,我需要使用弹出窗口。

Jir*_*vec 0

为什么不能使用这里描述的官方方式?https://www.npmjs.com/package/angularx-social-login

订阅 AuthState ofSocialAuthService

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);
    });
  }
 
}
Run Code Online (Sandbox Code Playgroud)

代码来自官方 NPM 包文档