【问题标题】:Angular Ignore leave page event when download file下载文件时Angular忽略离开页面事件
【发布时间】:2019-04-14 01:59:46
【问题描述】:

在我的 Angular 7 应用程序中,我有一个 canDeactivate 守卫来提醒用户未保存的更改。这个守卫也守卫不离开页面

  @HostListener('window:beforeunload')
  public canDeactivate(): boolean {
    return this.contentChanged === false;
  }

在同一页面上,我有一些从 AWS S3 下载的功能

  async downloadAttachment(url: string, e: any) {
    const target = e.target || e.srcElement || e.currentTarget;
    window.onbeforeunload = null;
    if (!target.href) {
      e.preventDefault();
      target.href = await this.storageService.getDownloadLink(
        url,
      );
      target.download = this.storageService.getFileName(url);
      target.click();
    }
  }

问题是当我有未保存的更改(contentChanged=true)时,下载会触发 window:beforeunload 事件,浏览器会发出警报

用户必须点击“离开”才能下载文件。下载过程实际上并没有离开页面。

我尝试在代码中添加“window.onbeforeunload = null”,但在我的代码中不起作用。

如何让用户在没有看到无意义警报的情况下进行下载?

【问题讨论】:

    标签: javascript angular dom-events


    【解决方案1】:

    您可以在防护中定义一个标志isDownloadingFile,并在开始下载之前设置它:

    constructor(private canDeactivateGuard: CanDeactivateGuard) { }
    
    async downloadAttachment(url: string, e: any) {
      const target = e.target || e.srcElement || e.currentTarget;
      if (!target.href) {
        e.preventDefault();
        this.canDeactivateGuard.isDownloadingFile = true; // <---------------- Set flag
        target.href = await this.storageService.getDownloadLink(url);
        target.download = this.storageService.getFileName(url);
        target.click();
      }
    }
    

    然后您将在canDeactivate 中检查并重置该标志:

    @Injectable()
    export class CanDeactivateGuard {
    
      public isDownloadingFile = false;
    
      @HostListener('window:beforeunload')
      public canDeactivate(): boolean {
        const result = this.isDownloadingFile || !this.contentChanged; // <--- Check flag
        this.isDownloadingFile = false; // <---------------------------------- Reset flag
        return result;
      }
    
      ...
    }
    

    【讨论】:

      猜你喜欢
      • 2015-08-12
      • 1970-01-01
      • 2011-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-14
      • 2013-05-04
      相关资源
      最近更新 更多