在我的应用程序中,有一个页面用户可以打开一个弹出窗口。当用户单击注销时,它必须关闭弹出窗口。
我在 Global.ts
类中使用静态变量存储弹出窗口变量
public static QUICKTREND : any;
在打开弹窗的功能中,我保存了
this.quickWin = window.open(URL, 'QuickTrend', 'width=' + w + ',
height=' + h + ', left=' + x + ', top=' + y + ', location=no'+ ', status=no');
Constants.QUICKTREND = this.quickWin;
在 logout() 函数中,我得到弹出窗口并关闭
if(!isNullOrUndefined(Constants.QUICKTREND)){
let currentIframe = Constants.QUICKTREND;
currentIframe.close();
}
如果我不刷新页面,它工作正常。
但是当我刷新页面时,变量 QUICKTREND 重置为未定义。
我搜索了在页面刷新时保持变量的解决方案,只有保存到 localStorage 或 sessionStorage 的解决方案。但是这样,我无法保存弹出窗口对象,因为它是 DOM 对象,Converting circular structure to JSON
错误显示。
localStorage.setItem("currentIframe", this.quickWin);
是否可以将弹出窗口保存到localStorage?
如果刷新页面,如何在注销时关闭弹出窗口?
最佳答案
你可以试试下面的代码:
app.component.ts
import { Component, HostListener } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular-Experiment';
public myWindow;
private URL = 'https://www.google.com/';
@HostListener('window:beforeunload', ['$event'])
closeOnrefresh(event) {
console.log('closeOnrefresh', event);
if (this.myWindow && !this.myWindow.closed) {
this.myWindow.close();
}
}
openWindow() {
console.log("open window");
if (!this.myWindow || (this.myWindow && this.myWindow.closed)) {
this.myWindow = window.open(this.URL, 'self', 'width=1000,height=1000');
} else {
this.myWindow.focus();
}
}
Winfocus() {
console.log("Winfocus");
if (this.myWindow && !this.myWindow.closed) {
// this.myWindow.close();// to close
this.myWindow.focus();// to focus
}
}
Logout() {
console.log("WinLogout");
if (this.myWindow && !this.myWindow.closed) {
this.myWindow.close();// to close
}
}
}
app.component.html
<input type="button" value="Open" (click)="openWindow()">
<input type="button" value="focus" (click)="Winfocus()">
<input type="button" value="Logout" (click)="Logout()">
关于javascript - 如果用户以 Angular 注销,则关闭弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54778060/