detecting the existence of window after reload - javascript

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

Related

How do I navigate to bing.com and enter a search text using the chrome console?

Below is my code.
It is resulting in unexpected behaviour.
It navigates to bing.com but it does not fill in the text field. Also, I have noticed that the console get cleared after navigating to a new webpage.
window.location = "https://www.bing.com";
window.onload = function(){
var editSearch = document.getElementById("sb_form_q");
editSearch.value = "Quux";
}
You are binding the onload function to the existing window object.
When the browser loads the new page, it will make a new window object which won't have your property set on it.
JavaScript run in one page (even when you are running it through developer tools) can't persist variables onto a different page.
(Storage mechanisms like localStorage and cookies are available, but you would need code in the subsequent page to look for them).
JavaScript is only valid for the current page you are on. When you are executing code from DevTools console, you are executing code on that page itself. So, when you navigate to another page using window.location you loose the onload handler you have defined.
To add handlers to a different page, it must be connected to your page (the parent) in some way, like an iframe or a popup.
ifrm = document.getElementById('frame');
ifrm.src = 'http://example.com';
ifrm.contentWindow.onload = function () {
// do something here with
// ifrm.contentWindow.document.getElementById('form')
}
As #Quentin said.
But you can do another way like ..
var keyword = "Quux";
window.location = "https://www.bing.com/search?q="+keyword;

Javascript: How to make sure window.open returns same window, if already opened

I am working on a web based application, in which I have to open popup window. I am using window.open() method to open the popup, like this:
window.open(url, "popupWin");
where url contains the URL I would like my popup window to navigate to. Now, the problem is, if I execute window.open() from multiple tabs (with same or different URLs), at least on Chrome, it might / might not give you the same window which was opened earlier. This behaviour is inconsistent, I mean, either it should get me fresh window every time, or it should get me previously opened window every time.
I need to persist the same popup window for entire domain. How can I do that?
Well looks like there is a direction to go or at least to give it a try.
It fully remains on localStorage which gives you ability to share the knowledge across your tabs within a single domain.
The code I give below does not work yet (it is only a direction), so don't expect too much from running it as it is.
What it does: it saves the popups by the url in a localStorage and when you try to open a new one with the same url it won't do that. If you don't want to distinguish them by URL it is even simpler: store boolean in a localStorage instead of an object.
What it does not do but should:
it should listen to the popup onunload (close) event and reset the localStorage information accordingly. Best for you here is just to set your localStorage boolean value to false
it should listen to the current tab onunload (reload, close) event and also reset something according to Your logic. As I understand the best for you would be just check whether this tab is the last one from your domain (you can also do this using localStorage, e.g. on every new tab adding its identifier, e.g. creation timestamp and destroying it on tab close) and if it is set your localStorage boolean value to false.
This, I think, would be enough to solve the problem. And finally a small piece of code:
// get the localstorage url map
function getOpenPopups() {
var obj = localStorage.getItem('mypopups');
return obj ? JSON.parse(obj) : {};
}
// set the localstorage url map
function setOpenPopups(object) {
localStorage.setItem('mypopups', JSON.stringify(object))
}
// open the popup
function popup(url, title) {
var popups = getOpenPopups();
// check whether popup with this url is already open
// if not then set it and open the popup
if (!popups[url]) {
popups[url] = true;
setOpenPopups(popups);
return window.open('abc', 'cde');
}
else {
return false;
}
}
jsFiddle
From w3c documentation we can see that window.open() returns a reference to the newly created window, or null if the call failed. That means we can keep it in memory and check for closed flag of that window.
var newWindow = window.open('/some/path', 'TestWindow');
// ...
if (!newWindow.closed) {
}
Keep in mind that if window with following name exists, page will be loaded in the same window without opening new one.
Other variants of name parameter like _blank, _self, _top, _parent you can find in official docs too.

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

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>

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