Check if window is already open window.open - javascript

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

Related

Firefox add-on: how to tell if a window is in the background

In a Firefox Add-on SDK add-on, how do I tell whether a window is in the background, ie. visible but not focused?
For example, if I bring a different application to the foreground, the Firefox window becomes unfocused but is still visible.
The reason why I want to do this is because I have a CPU-intensive content script running in the active window, and I'd like to pause it to avoid unnecessary overhead whenever the user isn't actively engaged with the window - meaning it's in the background or minimized.
require("sdk/windows").activeWindow keeps returning the last clicked window even if it's in the background or minimized. There doesn't seem to be any property for the window's focus state.
I can also get use the following code to get an nsIDocShell:
var mostRecentWindow = require("sdk/window/utils").getMostRecentBrowserWindow();
var docShell = require("sdk/window/utils").getWindowDocShell(mostRecentWindow);
Now when I query the docShell.isActive property, it returns true even if the window is in the background.
The one advantage of docShell.isActive is that it returns false when the window is minimized, while activeWindow returns true even in this case. But it's still missing information about whether the window is in the background or not.
Based on the suggestion by #willlma, this code seems to do the trick:
const windows = require('sdk/windows').browserWindows;
const tabs = require("sdk/tabs");
var anyWindowActive = true;
var refreshTimeoutId;
windows.on('deactivate', function(window) {
if (window == windows.activeWindow) {
anyWindowActive = false;
}
clearTimeout(refreshTimeoutId);
refreshTimeoutId = setTimeout(refreshTabStates, 50);
});
windows.on('activate', function(window) {
anyWindowActive = true;
clearTimeout(refreshTimeoutId);
refreshTimeoutId = setTimeout(refreshTabStates, 50);
});
tabs.on('activate', function(tab) {
clearTimeout(refreshTimeoutId);
refreshTimeoutId = setTimeout(refreshTabStates, 50);
});
function refreshTabStates() {
refreshTimeoutId = null;
for (let win of windows) {
for (let tab of win.tabs) {
var shouldBeActive = anyWindowActive
&& tab == tabs.activeTab
&& win == windows.activeWindow;
notifyTab(tab, shouldBeActive);
}
}
}
where notifyTab() is a function that posts a message to that tab's content script (if any) about whether it should be running or not.
setTimeout is used to avoid multiple calls to refreshTabStates in quick succession. For example, if you click on an inactive tab in a window that's not the current one, that one click results in window.deactivate, window.activate and tab.activate events.
Also, the initial state is a problem. What if the user launches Firefox and puts it in the background before any script has managed to run?

detecting the existence of window after reload

so suppose I do this
var myWindow = false;
$('someelement').click(function(){
var myWindow = window.open('url', 'name', 'width=100,height=200');
});
so the user clicks on the element on window A and a new window (call it window B) is opened...
but then suppose window A gets reloaded...due to this, var myWindow is now set to false...but then window B is still open....how can I detect the existence of Window B from window A after window A gets reloaded
I know that you can do this:
var hasWindow = window.open('', 'name');
and it will return a reference to window B if it's already open..
But then if window B is NOT opened yet, this will instead trigger a window opening, which is undesirable
How can I get a reference to window B if it's open without triggering a new window opening in the event in which window B is not open? (without resorting to cookie tricks)
The best way to keep a LITTLE bit of state without storing in cookies is to save something to your window.name. It'll only work with a string, though, so you'll need to save it as a JSON string if you want more than just a single bit of data.
To read:
var keptState;
if (window.name !== "") {
keptState = JSON.parse(window.name);
}
To write:
state = {
"popupOpened" : true,
"popupName" : "otherWindowName"
};
window.name = JSON.stringify(state);
On the other side of the refresh (or even navigating away from the site and back), it'll keep your variables you wanted. If you actually wanted a reference to the other window, however, you're on your own for that. I can't think of any way to determine that it's actually there. This would be a problem if, say, someone closed the popup window on their own.
At least this way, you can find out if you've opened it. Then you could do a popunder if you really needed that window without the popup. This always feels a little shady when I do it, but it's probably the best way to do what you're asking for.
var myWindow = window.open('', 'otherWindowName');
myWindow.blur();
window.focus();

JavaScript - Reference Browser Window by name? [duplicate]

This question already has answers here:
Access a window by window name
(7 answers)
Closed 4 years ago.
When you create a new browser window, you pass it a name like this:
myWindow = window.open('http://www.google.com', "googleWindow");
Later you can access the window from the variable you saved it as:
myWindow.close();
Is it possible to access and manipulate a window by it's name (googleWindow) instead of the variable?
If it is not possible, what is the point giving windows names?
No. Without a reference to the window, you can't find it again, by name or otherwise. There is no collection of windows.
UPDATE: Here's how you could do it yourself:
var windows = {};
function openWindow(url, name, features) {
windows[name] = window.open(url, name, features);
return windows[name];
}
Now, openWindow will always open the window, and if the window already exists, it will load the given URL in that window and return a reference to that window. Now you can also implement findWindow:
function findWindow(name) {
return windows[name];
}
Which will return the window if it exists, or undefined.
You should also have closeWindow, so you don't keep references to windows that you opened yourself:
function closeWindow(name) {
var window = windows[name];
if(window) {
window.close();
delete windows[name];
}
}
If it is not possible, what is the point giving windows names?
The name is used internally by the browser to manage windows. If you call window.open with the same name, it won't open a new window but instead load the URL into the previously opened window. There are a few more things, from MDN window.open():
If a window with the name strWindowName already exists, then strUrl is loaded into the existing window. In this case the return value of the method is the existing window and strWindowFeatures is ignored. Providing an empty string for strUrl is a way to get a reference to an open window by its name without changing the window's location. To open a new window on every call of window.open(), use the special value _blank for strWindowName.
Linus G Thiel says that you cannot do this in javascript. Oddly enough, his answer lists an excerpt from MDN that sounds like it tells how to do this. The line was:
"Providing an empty string for strUrl is a way to get a reference to
an open window by its name without changing the window's location."
I tried this and it works for me.
winref = window.open('', 'thatname', '', true);
winref.close();
However, this may only work if you opened the window from your page. And if that's true, then it's kind of pointless to do a window.open just to get the reference. You probably already have the reference, in that case.
Mark Goldfain's solution no longer works as written as of 9/8/2015
As per this w3 specification,
If the first argument is the empty string, then the url argument must
be interpreted as "about:blank".
I believe this is a difference between HTML4 and HTML5.
IE and Chrome have updated this behavior to match this specification, while Mark's solution still works on FF (though I imagine that they'll fix this soon). A few weeks ago this worked on all major browsers.
My particular problem involved window control while navigating, where the chat window opening is black boxed as well as most of the code on the page - redefining window.open was right out. My solution involved calling the blank window with the reference before calling the function which called the chat window. When the user navigated away from the page, I was able to rely on the fact that windows other than the original parent are not allowed to modify the child window, and so I was able to use Mark Goldfain's solution unchanged.
The solution provided by Mark Goldfain can be edited to work with the new browsers, at least to open a window and keep a reference to it between page refresh.
var winref = window.open('', 'MyWindowName', '', true);
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, '', true);
// 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');
I ended up using the following:
var newwindows = {};
function popitup(url, nm) {
if ((newwindows[nm] == null) || (newwindows[nm].closed)) {
newwindows[nm] = window.open(url, nm, 'width=1200,height=650,scrollbars=yes,resizable=yes');
}
newwindows[nm].focus();
}
then referenced using:
<button type="button" onclick="popitup('url/link.aspx?a=bc',this.value)" value="uniqueName">New</button>

Navigating Between HTML Windows

and thanks for taking a look at this seemingly simple question.
The scenario is as follows: I have a website Homepage named 'welcome.html'. From here users can select from a list of URLs and on clicking on the URL a simple Javascript function is called which opens a new Window.
Once the user has finished in the newly opened Window I want them to click on a button which calls a Javascript function to return them to the Homepage. It seems so simple.
However, if the Homepage Window is still open I want to return to this and not open another new Window displaying the Homepage. If the Homepage Window has been closed then I want a new Window to open displaying the Homepage.
I would be very grateful for some guidance here as I can't seem to get it to work.
Regards
Chris
As others have said, it is not the greatest design. However, I've run into scenarios like this in the past, where the business logic stipulates that a new window must be opened and there is no ability to change that.
As Pointy said, the biggest thing is just to keep track of the windows opened, and if you need some further help, perhaps this may help:
http://www.quirksmode.org/js/popup.html
But if possible, I would consider a different design (ask here if you need help implementing it!)
and thank you everyone who went to the trouble of sharing their thoughts.
I solved the problem in the following way:
When navigating from the Homepage to the new Window the following Javascript is used to open a new Window:
function popupFull(url)
// For explanation of this code see: http://www.quirksmode.org/js/popup.html
// Note: If fullscreen = 1 you can't see the menubar, toolbar, status etc.
// It is advisable to have no spaces around the commas in the parameters.
{
//alert("Opening: " + url)
// Prepare the parameter string
params = 'width='+screen.width;
params += ',height='+screen.height;
params += ',top=0,left=0';
params += ',fullscreen=0';
params += ',menubar=0';
params += ',toolbar=0';
params += ',directories=0';
params += ',status=0';
params += ',scrollbars=0';
params += ',resizable=1';
// Open a new window.
newWin=window.open(url, "fullWindow", params);
// If the current Window is in focus, switch focus to the new Window.
if (window.focus)
{
newWin.focus()
}
// Return the new Window object reference.
return newWin;
}
So the new Window can be opened and I have left the Homepage Window open but out of focus behind the new Window.
In the new Window there is a 'Menu' button. Clicking on this calls the following Javascript function:
function openMenu(winURL, winName, winFeatures)
{
// Create a reference of the Window which opened this Window. This should be
// the Main Menu Window.
var winObj=window.opener;
var menuOuterWidth = 1080;
var menuOuterHeight = 896;
var menuInnerWidth = 1068;
var menuInnerHeight = 767;
var menuX = (screen.width - menuOuterWidth) / 2;
var menuY = (screen.height - menuOuterHeight) / 2;
// Prepare the parameter string for re-opening the Menu
params = 'width='+menuInnerWidth;
params += ',height='+menuInnerHeight;
params += ',top='+menuY+',left='+menuX;
params += ',fullscreen=0';
params += ',menubar=1';
params += ',toolbar=1';
params += ',status=1';
params += ',scrollbars=1';
params += ',location=1';
params += ',resizable=1';
try
{
// Check to see if the window reference already exists.
if (winObj)
{
// Check to see if the Menu window is closed.
if (winObj.closed)
{
// The Menu window is closed.
// Open the Menu Window.
winObj = window.open(winURL, winName, params);
// Close this Course Window.
window.close();
// Return the Menu Window object reference should the caller want it.
return winObj;
}
else
{
// The Menu Window has not been closed. Set the Window's size and position.
// Note: When resizing the outerWidth/outerHeight value has to be passed.
winObj.window.resizeTo(menuOuterWidth, menuOuterHeight);
winObj.window.moveTo(menuX, menuY);
// Bring it into focus (bring to front).
winObj.focus();
// Close this Course Window.
window.close();
// Return the Menu Window object reference should the caller want it.
return winObj;
}
}
else
{
// The winObj object does not exist. Open the Menu.
winObj = window.open(winURL, winName, params);
// Close this Course Window.
window.close();
// Return the Menu Window object reference should the caller want it.
return winObj;
}
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.description + "\n\n";
txt+="Click OK to continue.\n\n";
//alert(txt);
// When IE6 tries to obtain the winObj.closed property, when the window is closed, it can cause
// an error "Permission Denied". This error is caught here. Open the Menu.
// Open the Menu Window.
winObj = window.open(winURL, winName, params);
// Close this Course Window.
window.close();
// Return the Menu Window object reference should the caller want it.
return winObj;
}
}
The comments should explain everything. The key is to get a reference to the Homepage Window where we started. (var winObj=window.opener;).
What caused me such a headache was that if I opened the new Window (using IE6), switched back to the Homepage and closed the Homepage Window, and then in the new Window clicked on the 'Menu' button nothing happened! I tried everything and then, after a cup of tea, realised that I would never write code in any application I was developing without any form of error capture. I added a Try, Catch statement and reported the error in an 'alert'. I got a 'Permission Denied' error.
After a lot of reading I figured I couldn't eliminate the error I would simply handle the error as elegantly as I could. This resulted in the code above.
It works a treat and I hope this helps someone.

window.open and searchpopop

We are use window.open for open popup. But then we want find it and close. Unfortunately we can`t save this popup handle to variable.
P.S. How get list of all windows?
This should work:
var wh = window.open(..)
wh is the handle to the popup window.
If you have control over the page that loads the script, you could do something like this. Warning: this is a really scary and generally bad thing to do:
<script>
var windowHandles = {};
(function() {
var realOpen = window.open;
window.open = function(url, name, features) {
windowHandles[name] = realOpen(url, name, features);
};
})();
</script>
That will build an object (windowHandles) in which the handles for each opened window will be saved.
Put that script in your page before the script that opens the other window is loaded.
I found not perfect solution, but it work.
win = window.open(null, 'Window1');
This code search search window with this name and return handler, but if window is closed it open empty popup.
I Think this is temporary solution
I don't like this solution. Fixing the script to give you a handle would be a better bet.
<button onclick="go()">Go</button>
<button onclick="stop()">Stop</button>
<script type="text/javascript">
function go() {
// Existing function. It opens a window with a name.
window.open('http://google.com', 'test', 'width=300,height=300');
}
var foo;
function stop() {
// Open a new window with the same name. It replaces the existing window.
// Since it opens a local document, the Same Origin Policy does not apply.
// ... and we can capture its return value to grab a handle on an existing
// window
foo = window.open('black-local-page.html', 'test', 'width=300,height=300');
// Give the local page time to load
setTimeout(continue_stopping, 500);
}
function continue_stopping() {
// Call window.open() on the window
foo.close();
}
</script>

Categories

Resources