如果使用X关闭Chrome显示通知对话框,则应用程序将失去焦点

时间:2019-03-06 14:39:56

标签: angular google-chrome

我有一个按钮,允许用户打开通知
(在意外的时间没有烦人的弹出窗口)

<span *ngIf="!showButton">
<div class="notificationsMsg">{{notificationMessage}}</div>
</span>
<span *ngIf="showButton">
<button mat-stroked-button
      id="sendButton"
      (click)="enableNotifications()">Enable Notifications</button>
</span>

单击按钮时
我显示“ Chrome允许通知”对话框
并响应用户的操作
然后隐藏按钮(您不能两次显示对话框)并显示一条消息

enter image description here

如果用户选择“阻止”或“允许”
一切都按预期进行
隐藏按钮,显示消息

如果用户使用X关闭对话框
我的代码会触发,但是在您手动单击页面

之前,页面不会更新

我是否可以在代码中做一些事情来再次赋予页面焦点以隐藏按钮并显示消息?

// the button was clicked
enableNotifications() {

Notification.requestPermission(perm => {
  if (perm === 'granted') {
    console.log('allow clicked');
    this.notificationMessage = 'Woo Hoo';
  } else  if (['default', 'denied'].indexOf(perm) > -1) {
    console.log('block clicked or dialog closed');
    this.notificationMessage = 'DENIED';
  }
  this.showButton = false;
});
}

Chrome版本72.0.3626.121(正式版本)(64位)

1 个答案:

答案 0 :(得分:1)

您必须在Angular zone中更新组件变量。

import { Component, OnInit, NgZone } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  name = 'Angular';
  notificationMessage = '';
  showButton: boolean;

  constructor(private zone: NgZone) { }

  ngOnInit() {
    Notification.requestPermission(perm => {
      if (perm === 'granted') {
        console.log('allow clicked');
        this.zone.run(() => {
          this.showButton = false;
          this.notificationMessage = 'Woo Hoo';
        });

      } else if (['default', 'denied'].indexOf(perm) > -1) {
        console.log('block clicked or dialog closed');
        this.zone.run(() => {
          this.showButton = false;
          this.notificationMessage = 'Denied';
        });
      }

    });
  }
}

Live Demo