Perform action after window closed - javascript

I have a JS that opens a new tab. And I want to refresh the original window but only once the opened tab is closed. How would you do it?
Here's the code I have now (which obviously doesn't work - it does the refresh immediately after opening the new window):
window.open( SOME_WINDOW );
window.location.reload();

You can do it with something like this. Store the window handle, and use a polling timer to check the closed property of the window.
var childwindow = window.open(SOME_WINDOW);
var timer = setInterval(function() {
if(childwindow.closed) {
clearInterval(timer);
window.location.reload();
}
}, 1000);
Another solution (even nicer) can be found here

Related

postMessage once the window loads successfully

I am trying to implement following feature
User opens up a page 1 on which there is a button. On clicking that button another window opens up but before that program checks whether the window is already open or not if it is already open than re-open the existing window or else open the new window.
While opening a window , I am passing some data to newly / existing open window using postMessage.
Now, the problem is when I am opening a window ( if it is NOT already open) then sometimes window is not able to receive the message sent by postMessage` hence I have used the setTimeout in following code.
However, this is not a reliable solution so I need a way where in newly open window receive the message each time.
Following is the code of service worker
let matchingClient = null;
for (let i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
if (windowClient.url === urlToOpen) {
matchingClient = windowClient;
break;
}
}
if (matchingClient) {
// if window is already open then just focus on window
matchingClient.focus();
// post the message
channel.postMessage({action: event.action,information:event.notification.data ? event.notification.data.info : ""});
} else {
//if window is not open yet, then open a new window
clients.openWindow(urlToOpen);
//have used setTimeout because opening a window may take time , however this is just a workaround
setTimeout(function(){
console.log("Delayed");
//post the message
channel.postMessage({action: event.action,information:event.notification.data ? event.notification.data.info : ""});
},4000);
}
});

Open link in new tab after X secs without pop up [duplicate]

This question already has answers here:
Open a URL in a new tab (and not a new window)
(33 answers)
Closed 7 years ago.
I tried several things, but everytime Chrome (and others?) detect a pop up... is possible to bypass it ?
window.open(
'/test.php',
'_blank'
);
}, 2000);
You would have to open the window using javascript, then set a setTimeout for two seconds that would wait for a variable to be set.
The new window would have to set a variable in the parent window to, lets say true.
Then with the setTimeout runs, it checks whether the variable is true, and if not, then opens the link. If it is, then do nothing
var didItOpen = false;
window.open('page.html');
setTimeout(function () { if (!didItOpen) location.href = 'page.html'; }, 2000);
Can you please try the code below?
//1000 = 1 second
setTimeout(function () {
window.open('url here', '_blank);
}, 1000);

setTimeout to window.open and close, on the same window?

I'm having a little difficulty opening up windows after a period of time, and then closing them after a period of time, automatically. I'm not sure why, but it seems like when I try to use setTimeout on a window.open and window.close they interfere somehow. Here is my code atm:
function topLeft() {
var myWindow = "image.png", "ONE", "width=300,height=310,top=100,left=100,menubar=no,toolbar=no,titlebar=no,statusbar=no";
setTimeout(function() {
myWindow.window.open() }, 5000);
setTimeout(function() {
myWindow.close() }, 10000);
function start() {
openClose();
}
window.onload = start;
Thanks for looking
Your code is just not right.
myWindow is a string variable.
You're trying to call myWindow.window.open(). This would generate a script error because myWindow (a string variable) does not have a window property.
Perhaps what you mean to do is this:
var myWindowURL = "image.png", myWindowName = "ONE";
var myWindowProperties = "width=300,height=310,top=100,left=100,menubar=no,toolbar=no,titlebar=no,statusbar=no";
var openWindow;
setTimeout(function() {
openWindow = window.open(myWindowURL, myWindowName, myWindowProperties);
}, 5000);
setTimeout(function() {
openWindow.close()
}, 10000);
Popup blockers in most popular browsers will only allow a new window to be opened if it is opened as a result of code running from a direct user action such as a click.
Because a setTimeout() happens some time in the future, is not considered the direct result of a user action so attempts to open windows from setTimeout() are likely blocked by the popup blocker.
You can, of course, disable the popup blocker in your own browser, but that is only something you can do in your own browser. You can't disable popup blocking via Javascript (as that would defeat the purpose).

Javascript detect closing popup loaded with another domain

I am opening a popup window and attaching an onbeforeunload event to it like this:
win = window.open("http://www.google.com", "", "width=300px,height=300px");
win.onbeforeunload = function() {
//do your stuff here
alert("Closed");
};
If I leave the URL empty, the new popup opens with "about:blank" as the address but when I close it, I see the alert.
If I open in as you see it (with an external URL), once it's closed, I cannot see the alert anymore. Any idea why this is happening?
As mentioned, same origin policy prevents Javascript from detecting such events. But there's a quite simple solution which allows you to detect closure of such windows.
Here's the JS code:
var openDialog = function(uri, name, options, closeCallback) {
var win = window.open(uri, name, options);
var interval = window.setInterval(function() {
try {
if (win == null || win.closed) {
window.clearInterval(interval);
closeCallback(win);
}
}
catch (e) {
}
}, 1000);
return win;
};
What it does: it creates new window with provided parameters and then sets the checker function with 1s interval. The function then checks if the window object is present and has its closed property set to false. If either ot these is not true, this means, that the window is (probably) closed and we should fire the 'closeCallback function' callback.
This function should work with all modern browsers. Some time ago Opera caused errors when checking properties from windows on other domains - thus the try..catch block. But I've tested it now and it seems it works quite ok.
We used this technique to create 'facebook-style' login popups for sites which doesn't support them via SDK (ehem... Twitter... ehem). This required a little bit of extra work - we couldn't get any message from Twitter itself, but the Oauth redireced us back to our domain, and then we were able to put some data in popup window object which were accessible from the opener. Then in the close callback function we parsed those data and presented the actual results.
One drawback of this method is that the callback is invoked AFTER the window has been closed. Well, this is the best I was able to achieve with cross domain policies in place.
You could listen to the 'focus' event of the opener window which fires when the user closes the popup.
Unfortunately, you're trying to communicate across domains which is prohibited by JavaScript's same origin policy. You'd have to use a server-side proxy or some other ugly hack to get around it.
You could try creating a page on your site that loads the external website in an iframe. You could then pop open that page and listen for it to unload.
I combined #ThomasZ's answer with this one to set an interval limit (didn't want to use setTimeout).
Example (in Typescript, declared anonymously so as not lose reference to "this"):
private _callMethodWithInterval = (url: string, callback: function, delay: number, repetitions: number) => {
const newWindow = window.open(url, "WIndowName", null, true);
let x = 0;
let intervalID = window.setInterval(() => {
//stops interval if newWindow closed or doesn't exist
try {
if (newWindow == null || newWindow.closed) {
console.info("window closed - interval cleared")
callback();
window.clearInterval(intervalID);
}
}
catch (e) {
console.error(`newWindow never closed or null - ${e}`)
}
//stops interval after number of intervals
if (++x === repetitions) {
console.info("max intervals reached - interval cleared")
window.clearInterval(intervalID);
}
}, delay)
}//end _callMethodWithInterval

Check if window is already open window.open

I have a html page. In the body of the page I am calling onload event which calls javascript function to open a pop up window. here is the code:
var newWindow = null;
function launchApplication()
{
if ((newWindow == null) || (newWindow.closed))
{
newWindow = window.open('abc.html','','height=960px,width=940px');
}
}
when I move to another page, and come back to that page again, popup reopens, although it is already opened. Please guide me to proper direction so that if pop up is already open then it should not open again. I tried document.referred but it requires the site online, currently I am working offline.
newWindow = window.open('abc.html','com_MyDomain_myWindowForThisPurpose','height=960px,width=940px');
Give the window a name. Basing the name on your domain like this, prevents the chances of you picking a name someone else happened to choose.
Never make up a name that begins with _, those are reserved for special names the browser treats differently (same as with the "target" attribute of anchor elements).
Note that if the window of that name was opened with different options (e.g. different height), then it'll keep those options. The options here will only take effect if there is no window of that name, so you do create a new one.
Edit:
Note that the "name" is of the window, not of the content. It doesn't affect the title (newWindow.document.title will affect that, as of course will code in abc.html). It does affect other attempts to do stuff across windows. Hence another window.open with the same name will reuse this window. Also a link like clicky! will re-use it. Normal caveats about browsers resisting window-opening in various scenarios (popup-blocking) apply.
To open a window and keep a reference to it between page refresh.
var winref = window.open('', 'MyWindowName', '');
if(winref.location.href === 'about:blank'){
winref.location.href = 'http://example.com';
}
or in function format
function openOnce(url, target){
// open a blank "target" window
// or get the reference to the existing "target" window
var winref = window.open('', target, '');
// if the "target" window was just opened, change its url
if(winref.location.href === 'about:blank'){
winref.location.href = url;
}
return winref;
}
openOnce('http://example.com', 'MyWindowName');
You can check if the window is open or closed by re-assigning a reference to it when it closes. Example:
var newWindow;
var openWindow = function(){
newWindow = newWindow || window.open('newpage.html');
newWindow.focus();
newWindow.onbeforeunload = function(){
newWindow = null;
};
};
Use the "closed" property: if a window has been closed its closed property will be true.
https://developer.mozilla.org/en-US/docs/Web/API/Window/closed
When you move on another page (on the same domain), you can re-set the window.open variable with popup page like this :
https://jsfiddle.net/u5w9v4gf/
Step to try :
Click on Run (on jsfiddle editor).
Click on Try me (on preview).
Click on Run to move on another page, the variable will be re-set.
Code :
window.currentChild = false;
$("#tryme").click(function() {
if (currentChild) currentChild.close();
const child = window.open("about:blank", "lmao", 'width=250,height=300');
currentChild = child;
//Scrope script in child windows
child.frames.eval(`
setInterval(function () {
if (!window.opener.currentChild)
window.opener.currentChild = window;
}, 500);
`);
});
setInterval(function() {
console.log(currentChild)
if (!currentChild || (currentChild && currentChild.closed))
$("p").text("No popup/child. :(")
else
$("p").text("Child detected !")
}, 500);

Categories

Resources