Javascript 下载文件时忽略离开页面事件
在我的Angular 7应用程序中,我有一个canDeactivate卫士来提醒用户未保存的更改。此防护装置还可防止离开页面Javascript 下载文件时忽略离开页面事件,javascript,angular,dom-events,Javascript,Angular,Dom Events,在我的Angular 7应用程序中,我有一个canDeactivate卫士来提醒用户未保存的更改。此防护装置还可防止离开页面 @HostListener('window:beforeunload') public canDeactivate(): boolean { return this.contentChanged === false; } 在同一页上,我有一些功能可以从AWSS3下载 async downloadAttachment(url: string, e:
@HostListener('window:beforeunload')
public canDeactivate(): boolean {
return this.contentChanged === false;
}
在同一页上,我有一些功能可以从AWSS3下载
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”,但在我的代码中不起作用
如何允许用户下载而不看到无意义的警报?您可以在guard中定义一个标志
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();
}
}
@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;
}
...
}