我想防止用户重复应用程序的选项卡,我正在使用 Angular 8.3.29。
这是我的代码:
ngOnInit() {
this.handleWindowLoad();
}
ngOnDestroy(): void {
this.handleBeforeUnload()
}
@HostListener('window:beforeunload', ['$event'])
onBeforeUnload(event: any) {
this.handleOnReloadClose();
}
handleWindowLoad() {
if (this.localStorageService.getSessionItem('windows') === AppConstant.API_CONFIG.SCREENCODES.PURCHASEENQUIRY) {
this.isscreenenabled = false;
} else {
this.localStorageService.addSessionItem('windows', AppConstant.API_CONFIG.SCREENCODES.PURCHASEENQUIRY);
this.isscreenenabled = true;
}
}
handleBeforeUnload() {
this.localStorageService.addSessionItem('windows', 'unknown');
}
handleOnReloadClose(){
this.localStorageService.removeSessionItem('windows');
}
重新加载页面时,ngOndestroy 不起作用,因此我无法重置存储中的值。当我关闭或重新加载副本时,主机侦听器会更新存储的值 选项卡,它应该只在主选项卡关闭或重新加载时更新值。是否有任何可行的选项来防止用户创建重复的选项卡
下面的示例会阻止用户打开新选项卡(如果已存在),并且在这种情况下将聚焦现有选项卡。
该示例允许通过提供唯一的
tabURL
和 tabName
值来处理任意数量的选项卡。请注意,窗口引用仅在应用程序的生命周期内存储,并且在刷新时会丢失。
windowObjectReference: Window | null = null; // global variable
public navigateToTab(event: MouseEvent): void {
this.openRequestedTab(tabURL, tabName);
event.preventDefault();
}
// open new tab or use existing if available
private openRequestedTab(url: string, windowName: string) {
if (
this.windowObjectReference === null ||
this.windowObjectReference.closed
) {
this.windowObjectReference = window.open(url, windowName);
} else {
this.windowObjectReference.focus();
}
}