The problem I am facing is in the scenario that one opens my site in a browser and eventually on clicking a link through open.window() method another window of the same domain is opened. Probability of user staying in both the windows are equal. Now I want to detect which window the user is in and throw a javascript popup there. Though the code must be in the parent window. I have tried window.opener() method but it is of no help. Please help.
I have edited a lot and put it here for demo.
setInterval((function(){
$("div.mask").css("display","");
}),10000);
$("div.mask,div.close").click(function(event) {
var $target = $(event.target);
if ($target.hasClass("mask") == true
|| $target.hasClass("close") == true) {
$("div.mask").css("display","none");
};
});
Now I want the masked popup to come at the top of all windows opened. Can we add .focus() to popup in jQuery?
I don't think you can know where the user "stays in". Better call your popup function in both windows. Just call your function and the popup will be opened where from it was called.
Anyway, I don't understand very well why you need to know which window the user is facing and what will open the popup.
Related
I have a window I'm opening with a Javascript function:
function newwindow()
{
window.open('link.html','','width=,height=,resizable=no');
}
I need it that once the new window opens that the focus returns to the original window.
How can I do that?
And where do I put the code - in the new window, or the old one?
Thanks!
This is known as a 'pop-under' (and is generally frowned upon... but I digress).. It should give you plenty to google about
You probably want to do something like:
var popup = window.open(...);
popup.blur();
window.focus();
Which should set the focus back to the original window (untested - pinched from google). Some browsers might block this technique.
After calling window.open, you may try to use
window.resizeTo(0,0);
window.moveTo(0,window.screen.availHeight+10);
this way can not really open window in background, but works in similar way. Chrome works fine, did not try other browser.
If Albert's solution doesn't work for you and you actually want the window visible, but to be opened behind the current window, you can try opening a new tab in the opener window and closing it right away, this will bring the focus back to the opener window.
window.open('link.html','','width=,height=,resizable=no');
window.open().close();
However, I believe whether the second window opens in a tab or a new window depends on your browser settings.
Please don't use "pop-unders" for evil.
You can use either
"blur" or
"focus" to do that required action.
"blur"
function newwindow()
{
var myChild= window.open('link.html','','width=,height=,resizable=no');
myChild.blur();
}
"focus"
function newwindow()
{
window.open('link.html','','width=,height=,resizable=no');
window.focus();
}
Put the code in your parentWindow (i.e. the window in which you are now)
Both will work.
tl;dr - in 2022 - ctrl/cmd clicking on a button and window.open(url, "_blank") in a javascript button handler's for loop will open multiple tabs in the background in Chrome.
I'm looking for this as of 2022 and none of the answers here worked (here and everywhere else I looked). My use case is clicking a button in a (progressive) web app which opens deep links to items in a list in background tabs (i.e. not "for evil").
It never occurred to me that ctrl/cmd + clicking on the button would open tabs in the background, but it does just as if the user clicked on an anchor tag itself directly - but only in Chrome. Combined with Chrome's relatively recent tab grouping feature, this can be very useful inside PWAs.
const isMozilla =
window?.navigator?.userAgent?.toString().toLowerCase().includes('firefox') ?? false;
for (let index = 0; index < urls.length; index++) {
const url = isMozilla ? urls.reverse()[index] : urls[index];
window.open(url, "_blank");
}
Note: I reverse() the array on Mozilla to get the order of newly created tabs as the user would expect them.
You can just use '_self'. It will be stay to the same page an
window.open(url, '_self');
I call below javascript on click of link/textbox or button.
function OpenPopupLinkRisk(Number)
{
window.open("../PopUp.aspx?id=" + Number, "List", "scrollbars=no,resizable=yes,width=700,height=450");
return false;
}
I donot want user to do anything else until he closes the popup window. So how can I grey background and force user to first close the popup and then do any other activity on application.
Can anyone suggest me how to achieve this ?
Thanks !
First of all, i would really disrecommend using window.open for this unless you really need a new browser popup window. If you want to stick with it persee, then will have to use a timer or something to manually check when the window is closed like:
var popup = window.open('http://www.example.com', 'example', '');
var timer = setInterval(function() {
if(window.closed) {
clearInterval(timer);
alert('Closed alright');
}
}, 100);
Else, check some tutorials on the subject, Modal Popup
First a direct solution to you problem that I wouldn't advice using it an then an approach you should be taking and is better from usability as well as security point of view.
Check whether popup window has closed
// mask your page
mask();
// open popup
var popup = window.open("../PopUp.aspx?id=" + Number);
// check whether it's been closed
function check()
{
if (popup && !popup.closed)
{
setTimeout(check, 1000);
}
// unmask your page
unmask();
}
check();
Modern (and better) alternative
Using window.open is a bad solution because it's a security risk and popup blockers prevent sites to open new windows. It's also considered bad practice.
A much better modern alternative is to display the new page as modal window inside your page directly. This will not open new windows and users stay as they are.
There are tons of javascript plugins for modal windows. Make a Google search.
I have the main page (called 'main.html'), with a link on it, with which I can open a popup or focus the popup if already existing: var test; if (test == null || test.closed) test = window.open('test.html','test','width=800,height=600,location=0'); else test.focus();
Works fine, but here comes the problem: If the user opens the main page more than one time in his browser, clicks the link in main #1 and then clicks the link in main #2, it uses the existing popup, but reloads the site, because he doesn't know, that the popup is already opened.
Is there a way, that I can tell the other main windows the handle of the popup, so they can use it?
Thanks for your advise.
If the two "main windows" are opened independently from each other, there is no way for them to access the variables of each other.
You can however get a reference to the window "test" with window.open, and then check if a variable you set in "test.html" is defined, to find out if it it's loaded:
var test;
if (!test || test.closed) {
test = window.open('','test','width=800,height=600,location=0');
if (test && !test.someVariable) {
test.location.href = "test.html";
}
} else
test.focus();
BTW, notice I changed the check in the first if from test == null to !test, because the variable will be originally undefined and not null, so that test == null will result in false.
This would need you to being able to access the main window in all the other tabs to check whether any of them have opened a popup. As far I know the only way to get a reference to a window is from the reference returned by the function window.open.
Not allowing javascript to accessing other windows and tabs except inside the window which opened the windows/tabs is due to security. Imagine if javascript could go through all your tabs and run functionality. That would be quite a big security risk.
I've seen ways of seeing if a window a particular script opened is still opened, but what if it didn't?
I have a small window that has a button to click to load the large window. When I close the large one, I want a particular onUnload or onBeforeUnload to fire iff the small one is closed; if it's still open, those procedures will not fire. I may be having simply a massive brain fart but I can't figure out how to check if the other window is open. The big one isn't opening it, so I can't simply record the handle from opening it.
In shorter terms: If window A opened window B, how can I check within window B if window A still exists?
if(window.opener && !window.opener.closed)
alert('Yup, still there.');
window.closed will be set to true if you popped a window and it was closed (by script or user).
var win = window.open('...')';
if (win.closed)
Your case seems to be the following:
From a popup window, you can check if the window that opened it is still open using window.opener.closed
Get handle to a window by name
I mentioned there's no way to just get the window handle by name in the comments. However, I did some research and found that the following works in FF/IE/Chrome; it's a hack, I didn't see it mentioned anywhere as the expected behavior, so I wouldn't rely on it too much, but it was fun to find it works! In my code, I would still just make sure to pass around the required handles.
//opened a window without storing a handle, but gave it a name
window.open('/some/url', 'xxx');
// now I need to get a reference to that window
// Calling open without setting a url gets you
// a reference and doesn't reload the window
var win = window.open('', 'xxx')
Use try{} and catch(err){}.
try{
window.opener.document.body.getElementById('#elementId'); // do some action with window. opener
}
catch(err){
// if we are here then probably there is no window.opener
window.close(); // closing this window or whatever you want
}
Try the following code:
if (!!window) {
console.log('Exist');
}
I have two pages one.html and two.html
I am opening a new window using following code
//here popup is a global variable
popup=window.open('two.html','two');
for the first time a popup window open successfully and get the focus but
if I try to open it again without closing already opened popup then two.html is not getting focus for the second time.
note: I have set popup window's name as 'two'
You can use the focus function, as used below:
<script language="javascript" type="text/javascript">
<!--
function popitup(url) {
newwindow=window.open(url,'name','height=200,width=150');
if (window.focus) {newwindow.focus()}
if (!newwindow.closed) {newwindow.focus()}
return false;
}
// -->
</script>
focusedWindow = window.open('two.html','two').focus();
Directly append the focus() to the window.open protoype
My empiric solution that always works:
setTimeout('detail.focus()', 1);
Appending .focus() right after open does not always work, nor calling a .focus() without setTimeout.
I know it's ugly (wanted to get rid of it right now, after some years, with no success), and I do not know the exact reasons why and how, but it works.
You can close the popup before you open it if you check to see if the popup is already open when you call the function.
var popup;
function openPop() {
if ("close" in popup) popup.close();
popup = window.open("http://stackoverflow.com", "test", "width=200, height=200");
}
This will ensure the popup always appears on top.
var win = window.open('two.html','two');
win.document.getElementsByTagName("body")[0].focus(); //focus the body rather than the window.
Check your Firefox 2 settings at
Go to Tools -> Options -> Content
Make sure "Enable JavaScript" is turned on.
Next to "Enable JavaScript", click the "Advanced" button.
Make sure that there is a check-mark in the box
[x] Raise or lower windows
If the setting "Raise or lower windows" is turned off, then
this disables the window.focus() method.
I found an answer for myself that works. In the html of the popup body, add to the body tag onload="this.window.focus()". Even if you minimize the window, it pops back up front and center. Be sure and name the window in your execution script window.open('url','some name','vars'); Hope this helps you!
Unfortunately some modern browsers still don't support focusing tabs, see this Firefox bug entry, for example.
However, the following code is working well for me. As a workaround, it reopens a window/tab if it cannot be focussed:
var win = window.open("two.html", "two")
win.focus();
setTimeout(function() {
if(document.hasFocus()) {
win.close();
window.open("two.html", "two")
}
}, 1);
In the first line it opens the window and tries to focus it using the second line. If a window with the name two is already there, no new window/tab is opened, but it's reused.
The trick now is, that we check if the current window still has focus using document.hasFocus(). If so, we close the window and reopen it. This is only for browsers which don't support focusing the tab which is to be reused directly. Currently, this is the case for FF and IE/MS Edge. Chrome works well.
However, directly after using window.open, document.hasFocus() always returns true (so said, also in Chrome). The workaround is to use setTimeout one ms later.
just add .focus() to the window.open line
window.open('two.html','two').focus()
I did have same problem and this seems to work in both Firefox and Chromium web browsers.
In my web thaiiceland.com I noticed that if the popup was open, the focus didn't go on the popup and you feel nothing happen when you click on that link. So I search and after try to just add .focus() in the end of the window.open line it works.
Curency converter - แปลงสกุลเงิน
setTimeout(function () {
window.open('PageName', '', 'height=560,width=1120,resizable=no,left=100,top=50,screenX=100,screenY=50');
}, 100);
-> This code is use for giving focus on newly open window.
-> Put it in javascript.('setTimeout is inbuilt function of javascript')
-> Many time happen that when popup window is opened, it will go behind the old window, So above is very useful to focus for new window.
It is a one liner solution, use focus on your pop up var:
popup=window.open('two.html','two');
popup.focus();
This will always open your pop up window even if it is not closed.