I am relatively new in frontend, I am trying to open a new url if the button is clicked. My target is if the url is already opened in a seperate tab, then just switch to that tab. Else, open the url in a new tab and switch to it.
I have went through some documentations and stackoverflow solutions, for example this.
I also added the following code in my class, but it opens a new window always.
openOrCloseChildWindow(
childWindowUrl: string,
childWindowName: string,
childWindowFeatures: string
) {
let childWindow: Window | null = null;
function openChildWindow() {
// open the child window and give it the specified name and features
childWindow = window.open(childWindowUrl, childWindowName);
// listen for messages from the child window
window.addEventListener('message', onChildWindowMessage);
}
function onChildWindowMessage(event: MessageEvent) {
// check if the message is from the child window, and has the correct format
if (event.source === childWindow && event.data === 'childWindowAlive') {
// the child window is still open, do nothing
} else {
// the message is not from the child window, or has the wrong format, close the child window
closeChildWindow();
}
}
function closeChildWindow() {
// check if the child window is still open
if (childWindow && !childWindow.closed) {
// send a message to the child window to tell it to close itself
childWindow.postMessage('closeChildWindow', '*');
}
// stop listening for messages from the child window
window.removeEventListener('message', onChildWindowMessage);
// close this window
window.close();
}
// check if the current window was opened by another window
if (window.opener && !window.opener.closed) {
// send a message to the parent window to confirm that the child window is still open
window.opener.postMessage('childWindowAlive', '*');
} else {
// open the child window
openChildWindow();
}
}
Is there any way I could make this code work or if you have any solutions, please suggest.
I was trying to open a new tab if it is not exist, if exist switch to that tab.
I tried some existing solutions which does not work. I also tried to write a solution myself.