Reputation: 18975
In my application, has a page user can open an popup window. When user click logout it must close popup window.
I use a static variable for store popup window variable in Global.ts
class
public static QUICKTREND : any;
In function to open popup window, i stored it
this.quickWin = window.open(URL, 'QuickTrend', 'width=' + w + ',
height=' + h + ', left=' + x + ', top=' + y + ', location=no'+ ', status=no');
Constants.QUICKTREND = this.quickWin;
In logout() function I get popup window and close
if(!isNullOrUndefined(Constants.QUICKTREND)){
let currentIframe = Constants.QUICKTREND;
currentIframe.close();
}
It worked correct if I did not refresh page.
But when I refresh page, variable QUICKTREND reset to undefined.
I searched solution to keep variable if page is refresh, only solution to save to localStorage or sessionStorage. But this way, I can not save popup window object because it is DOM object, Converting circular structure to JSON
error show.
localStorage.setItem("currentIframe", this.quickWin);
Is it possible to save popup window to localStorage?
How can I close popup window when I logout if page is refresh?
Upvotes: 0
Views: 3755
Reputation: 266
You can try the below code:
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()">
Upvotes: 2