我在addEventListener和postMessage方面遇到问题。 我有登录对话框,还有一个用于登录Facebook的按钮。当用户单击此按钮时,将打开窗口以使用Facebook登录。然后用户提交Facebook表单,页面将被重定向到我的静态HTML页面,该页面使用postMessage转发一些信息。我有addEventListener和handleMessage方法,它们必须处理从静态HTML页面发送的所有消息,但是handleMessage方法可以工作很多次,该方法可以处理我不使用postMessage发送的消息。
登录组件:
constructor(public thisDialogRef: MatDialogRef<SigninComponent>, private auth: AuthService,
private userService: UserService, private router: Router,
private alertwindow: AlertWindowsComponent) {
if (window.addEventListener) {
window.addEventListener("message", this.handleMessage.bind(this), false);
}
else {
(<any>window).attachEvent("onmessage", this.handleMessage.bind(this));
}
}
launchFbLogin() {
this.authWindow = window.open(`https://www.facebook.com/v3.2/dialog/oauth?&response_type=token&display=popup&client_id=318651702058203&display=popup&redirect_uri=${this.url}facebook-auth.html&scope=email`,null,'width=600,height=400,top=400,left=400');
}
handleMessage(event: Event) {
const message = event as MessageEvent;
...
}
在静态HTML文件中应用方法postMessage:
window.opener.postMessage(JSON.stringify(message), "http://localhost:4200");
答案 0 :(得分:0)
我不确定这是否有助于解决您的问题。根据您发送评论的逻辑,您需要在代码中添加一个标志,以检查处理程序的状态,以避免重复调用。
handlerState = 0; // 0 - Not started, 1 - Being processed, 2 - Processed
constructor(public thisDialogRef: MatDialogRef<SigninComponent>, private auth: AuthService,
private userService: UserService, private router: Router,
private alertwindow: AlertWindowsComponent) {
if (window.addEventListener) {
window.addEventListener("message", this.handleMessage.bind(this), false);
}
else {
(<any>window).attachEvent("onmessage", this.handleMessage.bind(this));
}
}
launchFbLogin() {
this.authWindow = window.open(`https://www.facebook.com/v3.2/dialog/oauth?&response_type=token&display=popup&client_id=318651702058203&display=popup&redirect_uri=${this.url}facebook-auth.html&scope=email`,null,'width=600,height=400,top=400,left=400');
}
handleMessage(event: Event) {
if (handlerState != 0) {
return; // Already being processe or processed already.
}
handlerState = 1;
const message = event as MessageEvent;
...
handlerState = 2;
}