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

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).

Related

New window in ajax call blocked

I've searched on the internet for a while for my solution, but none of the solutions worked for me or I didn't used it correct (I think).
I have a function which looks like this and is being called when a image is clicked:
function goToGoogle() {
setTimeout(function() {
$.ajax("url/path", {
data: "data"
}, function(data){
window.open("https://www.google.nl", "_blank");
});
}, 10000);
}
When window.open is called, a message pops up and says that the popup is blocked.
I've tried to create a variable with window.open in it (var myWindow = window.open( ... );) and then set the correct url with myWindow.location = "www.correct.url";. But this will result in a error in the console.log, which says that myWindow is undefined and location can't be called because of that.
Another thing I tried was to set async to false in the ajax call, but that's depreciated.
Does anyone how to make sure it opens a new window, even a few seconds after the click event?
By the way, I need the timeout of 10 seconds.. Nothing more, nothing less.
Your code works perfectly, because
a message pops up and says that the popup is blocked.
That's just a browser policy to block popups. That's up to user to allow open popups on your site or to forbid.

Adding Tab on Window Load for Firefox Extension

I want to add a tab whenever a new Firefox window is loaded for my bootstrap extension. I use this code listing:
var WindowListener = {
setupBrowserUI: function(window) {
window.gBrowser.selectedTab=window.gBrowser.addTab("http://google.com");
},
tearDownBrowserUI: function(window) {
},
// nsIWindowMediatorListener functions
onOpenWindow: function(xulWindow) {
var domWindow = xulWindow.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
// Wait for it to finish loading
domWindow.addEventListener("load", function listener() {
domWindow.removeEventListener("load", listener, false);
// If this is a browser window then setup its UI
if (domWindow.document.documentElement.getAttribute("windowtype")=="navigator:browser") domWindow.gBrowser.selectedTab=domWindow.gBrowser.addTab("http://google.com");
}, false);
},
onCloseWindow: function(xulWindow) {
},
onWindowTitleChange: function(xulWindow, newTitle) {
}
};
let wm = Components.classes["#mozilla.org/appshell/window-mediator;1"].
getService(Components.interfaces.nsIWindowMediator);
// Wait for any new browser windows to open
wm.addListener(WindowListener);
You can try it in Scratchpad.
onOpenWindow method have the code to open tab in new window but it executes before the window is loaded completely so adding tab in this state does not seem to work although MDN code says "Wait for it to finish loading".
Setting a timeout by setTimeout function does the job but it looks ugly.
domWindow.setTimeout(function(){domWindow.gBrowser.selectedTab=domWindow.gBrowser.addTab("http://google.com");},1000);
Is it possible to add tab for new Firefox windows after window completely is loaded without setTimeouts?
I'd go with a setTimeout(..., 0) hack. That ought to be the most reliable option and is used throughout the Firefox code itself :p
if (domWindow.gBrowser) {
setTimeout(function() {
domWindow.gBrowser.selectedTab =
domWindow.gBrowser.addTab("http://google.com");
}, 0);
}
It's really weird. I can't explain it. But from the line:
if (domWindow.document.documentElement.getAttribute("windowtype")=="navigator:browser") domWindow.gBrowser.selectedTab=domWindow.gBrowser.addTab("http://google.com");
remove the domWindow.gBrowser.selectedTab = so change it to:
if (domWindow.document.documentElement.getAttribute("windowtype")=="navigator:browser") {
domWindow.gBrowser.addTab("http://google.com");
}
this succesfully loads the url BUT it doesnt select the tab SO I tried and absolutely new idea why this stuff FAILED:
if (domWindow.document.documentElement.getAttribute("windowtype")=="navigator:browser") {
var tab = domWindow.gBrowser.addTab("http://google.com");
}
as soon as i put that var tab = in front it fails. If it didn't fail i was planning to put on next line: domWindow.gBrowser.selectedTab = tab
THEN this also fails:
loadOneTab has inBackground parameter, if set it to false it will focus the tab:
if (domWindow.document.documentElement.getAttribute("windowtype")=="navigator:browser") {
domWindow.gBrowser.loadOneTab("http://google.com", {inBackground:false});
}
Absolutely no idea but this fails to load url but it focuses the tab. If you set inBackground to true it loads the url and of course it wont focus the tab. Absolutely weird...
Posted so others can maybe find out where the problem is, maybe we need to report something on bugzilla.

closing the current tab in a chrome extention

I am writing a chrome extension that when clicked, will close the current tab after a given amount of time.
I am sending a message with the time, from popup.js to background.js. But the tab won't close.
The alert works when I uncomment it, so it seems to be just the remove line. I assume it's something about tab.id.
chrome.extension.onMessage.addListener(
function message(request, sender, callback) {
var ctr = 0;
ctr = parseInt(request.text, 10);
setTimeout(function() {
chrome.tabs.getCurrent(function(tab) {
//window.alert("Working?");
chrome.tabs.remove(tab.id, function(){});
});
}, ctr);
}
);
1.
chrome.extension has no onMessage event. I assume you mean the correct chrome.runtime.onMessage
2.
You have probably misunderstood(*) the purpose of chrome.tabs.getCurrent:
Gets the tab that this script call is being made from. May be undefined if called from a non-tab context (for example: a background page or popup view).
Since, you are calling it from a non-tab context (namely the background page), tab will be undefined.
(*): "misunderstood" as in "not bother to read the manual"...
3.
It is not clear if you want to close the active tab at the moment the timer is set or at the moment it is triggered. (In your code, you are attempting to do the latter, although the former would make more sense to me.)
The correct way to do it:
chrome.runtime.onMessage.addListener(function message(msg) {
var ctr = 0;
ctr = parseInt(msg.text, 10);
setTimeout(function() {
chrome.tabs.query({ active: true }, function(tabs) {
chrome.tabs.remove(tabs[0].id);
});
}, ctr);
});
Also, note that using functions like setTimeout and setInteval will only work reliably in persistent background pages (but not in event pages). If possible, you are advised to migrate to event pages (which are more "resource-friendly"), in which case you will also have to switch to the alarms API.

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

Perform action after window closed

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

Categories

Resources