focus only working with alert - javascript

I have the following, rather simple function:
function takeFocus() {
setTimeout(function(){window.focus();alert("OK");},1000);
}
This is within the JavaScript of a window I have opened from another window.
When the user re-opens the sub-window, I want to switch to it, and bring it to the front, without reloading it. Calling takeFocus() as above works just fine, but it throws up the prompt, which I don't want.
When I remove the alert, the background window stays in the background! How can I make it work?
I have tried all sorts of ways to do this, and so far I have failed.
jQuery is available. Writing for modern browsers in HTML5.

Is this code in the sub-window file?
Try use the focus in the main page like this:
function newPopup(url) {
popupWindow = window.open(
url,'popUpWindow3','height=500,width=900,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no,status=no');
popupWindow.focus();
}

I have half an answer. By using this code to open the window, I get the behaviour I need in Chrome. Sadly FireFox 23.01 and IE 10 are still ignoring the win.focus().
function openWin(ID) { // open workshop ID in another window
var URL = '/chatroom.php?ID='+ID;
var name = 'Chat'+ID; // so if you open it twice it reopens the window.
var win = window.open('',name); // no URL - won't refresh
if (win.location == "about:blank") { // new open
win.location.href = URL;
windows[windows.length] = win; // store for later.
}
win.focus();
}
FF and IE open the window OK the first time, and they don't refresh and lose the data on the second pass, but they don't bring it to the foreground either :(

Related

How would I open a new window that doesn't focus as it's opened [duplicate]

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

JavaScript confirm dialog in new window/tab

I have a confirm dialog appearing on a form, which redirects the user to another page when clicked on ok.
However, is it possible to have that page open in a new window (e.g. target="_blank")
The code that I'm using is:
var answer=confirm("Do u want to continue?") {
if (answer==false) {
document.form.field1.focus();
return false;
}
window.location.href = "/some/url"
}
So window.location refers to the location of your current window, so changing it of course takes you away from the window you're on. To open a new window, you want window.open - see Open a URL in a new tab (and not a new window) using JavaScript
However, I'd suggest instead, using a link that you intercept the default behavior for if the user answers false, and otherwise fallback to the default behavior.
ie:
bar
$('#foo').click(function(e){
var answer=confirm("Do u want to continue?") {
if (answer==false) {
document.form.field1.focus();
e.preventDefault();
}
}
});
Although I'd have to double check if that actually works, I haven't worked with confirm much at all, so you might have to call the e.preventDefault() outside of that block.
window.open(
'/some/url',
'_blank'
);

html open a url on new target and focus

I am trying to fix a web site.
It opens a help page in a new window/tab via <a href="..." target="help"> (no other frame has this name)
This works well the first time opening a new window/tab, for the help.
But on subsequent clicks the window/tab is loaded but remains hidden.
I tried this:
<script>
function OpenAndFocusHelp() {
win=window.open('help/1000CH00017.htm','help');
win.focus();
}
</script>
<a href="help.html" target="help"
onclick="OpenAndFocusHelp()">Help</a>
It did not work!
It seems that modern browsers do not allow you to window.focus an existing window. Or at least, it will not give that window focus. (IE9 will actually blink the tab, but most other browsers merely load it but give no indication that the user's attention should be drawn to the new window.)
Therefore, one solution that presents itself is to close the window first, and then re-open it immediately after. For example, declare the following function:
window.openOrFocus = function(url, name) {
if (!window.popups)
window.popups = {};
if (window.popups[name])
window.popups[name].close();
window.popups[name] = window.open(url, name);
}
Now, you can write HTML such as this:
Window 1<br />
Window 2<br />
Since it closes the window first, it reliably gives focus to the newly created child window.
This solution also uses the window.popups namespace, so rename the usages of that in the javascript sample if you have a function named popups or have otherwise collided with it.
Caveat: This does not work after a post-back. This is because once you navigate away from the current page, it is no longer the owner of the child windows. Therefore, it can no longer close them. However, it merely degrades to the usual (non-focusing) behavior of using the target attribute.
Tested In: Firefox 4, Chrome 11, IE 9
JsFiddle Demo: http://jsfiddle.net/aqxBy/7/
I think this feature is browser-specific and you can't define the behavior for focusing new tabs or windows..
You can have such code instead:
var _arrAllWindows = new Array();
function OpenOrFocus(oLink, sTarget) {
var oWindow = _arrAllWindows[sTarget];
if (!oWindow || oWindow.closed) {
oWindow = window.open(oLink.href, sTarget);
_arrAllWindows[sTarget] = oWindow;
}
oWindow.focus();
return false;
}
Then to call it, have such link:
Open
Works fine in Chrome and IE, unfortunately Firefox disable by default the option to "raise" windows in code so focus() has no effect in that browser - could not find any work around.
Test case is available here: http://jsfiddle.net/yahavbr/eVxJX/
Here's one way using jQuery and HTML5 with fallback for JavaScript-disabled clients. It will reload pages on every click. Tested and works in Firefox and Chrome.
<script>
$(document).ready(function() {
$('a[data-popup]').click(function(event) {
event.preventDefault();
window.open(this.href, this.dataset['popup'], 'resizable,scrollbars').focus();
});
});
</script>
Stack Overflow
Super User
Server Fault

In Google Chrome, how do I bring an existing popup window to the front using javascript from the parent window?

I would like to have a button on a web page with the following behavior:
On the first click, open a pop-up.
On later clicks, if the pop-up is still open, just bring it to the front. If not, re-open.
The below code works in Firefox (Mac & Windows), Safari (Mac & Windows), and IE8. (I have not yet tested IE6 or IE7.) However, in Google Chrome (both Mac & Windows) later clicks fail to bring the existing pop-up to the front as desired.
How can I make this work in Chrome?
<head>
<script type="text/javascript">
var popupWindow = null;
var doPopup = function () {
if (popupWindow && !popupWindow.closed) {
popupWindow.focus();
} else {
popupWindow = window.open("http://google.com", "_blank",
"width=200,height=200");
}
};
</script>
</head>
<body>
<button onclick="doPopup(); return false">
create a pop-up
</button>
</body>
Background: I am re-asking this question specifically for Google Chrome, as I think I my code solves the problem at least for other modern browsers and IE8. If there is a preferred etiquette for doing so, please let me know.
You can't. Window.focus is disabled in Chrome for security reasons, and that is unlikely to change.
You have to close and repopen the respective window.
Why not just do a popopWindow.focus() after the window.open call? It won't hurt to do it there too, and it should ensure that your new window is shown on top of the current one.
You need to set original window to blur and the new window to focus.
var popup = { //popup = object literal representing your popup
execute = (function () {
popup.win = window.open();
popup.win.focus();
}());
};
window.blur();
The following code works for me when called in a onclick handler:
var popup = window.open('', 'popup-name', 'resizable,width=480=height=575');
if(popup.location == 'about:blank') {
popup.location = 'http://google.com';
return;
}
This code works by trying to access the popup's location, if its about:blank its a new popup and the url is set. Otherwise if the window with the same name 'popup-name' is already open the popup comes into focus. This code does need to be called from a onclick handler otherwise it will not work.
As of today, just calling focus() on the reference to the popup just works and brings the window to the front. I am using Chrome version 62

JavaScript open in a new window, not tab

I have a select box that calls window.open(url) when an item is selected. Firefox will open the page in a new tab by default. However, I would like the page to open in a new window, not a new tab.
How can I accomplish this?
Specify window "features" to the open call:
window.open(url, windowName, "height=200,width=200");
When you specify a width/height, it will open it in a new window instead of a tab.
See https://developer.mozilla.org/en-US/docs/Web/API/Window.open#Position_and_size_features for all the possible features.
You don't need to use height, just make sure you use _blank, Without it, it opens in a new tab.
For a empty window:
window.open('', '_blank', 'toolbar=0,location=0,menubar=0');
For a specific URL:
window.open('http://www.google.com', '_blank', 'toolbar=0,location=0,menubar=0');
I may be wrong, but from what I understand, this is controlled by the user's browser preferences, and I do not believe that this can be overridden.
Try:
window.open("", [window name], "height=XXX,width=XXX,modal=yes,alwaysRaised=yes");
I have some code that does what your say, but there is a lot of parameters in it. I think these are the bare minimum, let me know if it doesn't work, I'll post the rest.
OK, after making a lot of test, here my concluson:
When you perform:
window.open('www.yourdomain.tld','_blank');
window.open('www.yourdomain.tld','myWindow');
or whatever you put in the destination field, this will change nothing: the new page will be opened in a new tab (so depend on user preference)
If you want the page to be opened in a new "real" window, you must put extra parameter. Like:
window.open('www.yourdomain.tld', 'mywindow','location=1,status=1,scrollbars=1, resizable=1, directories=1, toolbar=1, titlebar=1');
After testing, it seems the extra parameter you use, dont' really matter: this is not the fact you put "this parameter" or "this other one" which create the new "real window" but the fact there is new parameter(s).
But something is confused and may explain a lot of wrong answers:
This:
win1 = window.open('myurl1', 'ID_WIN');
win2 = window.open('myurl2', 'ID_WIN', 'location=1,status=1,scrollbars=1');
And this:
win2 = window.open('myurl2', 'ID_WIN', 'location=1,status=1,scrollbars=1');
win1 = window.open('myurl1', 'ID_WIN');
will NOT give the same result.
In the first case, as you first open a page without extra parameter, it will open in a new tab. And in this case, the second call will be also opened in this tab because of the name you give.
In second case, as your first call is made with extra parameter, the page will be opened in a new "real window". And in that case, even if the second call is made without the extra parameter, it will also be opened in this new "real window"... but same tab!
This mean the first call is important as it decided where to put the page.
You might try following function:
<script type="text/javascript">
function open(url)
{
var popup = window.open(url, "_blank", "width=200, height=200") ;
popup.location = URL;
}
</script>
The HTML code for execution:
google search
You shouldn't need to. Allow the user to have whatever preferences they want.
Firefox does that by default because opening a page in a new window is annoying and a page should never be allowed to do so if that is not what is desired by the user. (Firefox does allow you to open tabs in a new window if you set it that way).
The key is the parameters :
If you provide Parameters [ Height="" , Width="" ] , then it will open in new windows.
If you DON'T provide Parameters , then it will open in new tab.
Tested in Chrome and Firefox
I just tried this with IE (11) and Chrome (54.0.2794.1 canary SyzyASan):
window.open(url, "_blank", "x=y")
... and it opened in a new window.
Which means that Clint pachl had it right when he said that providing any one parameter will cause the new window to open.
-- and apparently it doesn't have to be a legitimate parameter!
(YMMV - as I said, I only tested it in two places...and the next upgrade might invalidate the results, any way)
ETA: I just noticed, though - in IE, the window has no decorations.
For me the solution was to have
"location=0"
in the 3rd parameter. Tested on latest FF/Chrome and an old version of IE11
Full method call I use is below (As I like to use a variable width):
window.open(url, "window" + id, 'toolbar=0,location=0,scrollbars=1,statusbar=1,menubar=0,resizable=1,width=' + width + ',height=800,left=100,top=50');
Interestingly, I found that if you pass in an empty string (as opposed to a null string, or a list of properties) for the third attribute of window.open, it would open in a new tab for Chrome, Firefox, and IE. If absent, the behavior was different.
So, this is my new call:
window.open(url, windowName, '');
try that method.....
function popitup(url) {
//alert(url);
newwindow=window.open("http://www.zeeshanakhter.com","_blank","toolbar=yes,scrollbars=yes, resizable=yes, top=500, left=500, width=400, height=400");
newwindow.moveTo(350,150);
if (window.focus)
{
newwindow.focus()
}
return false;
}
Answered here. But posting it again for reference.
window.open() will not open in new tab if it is not happening on actual click event. In the example given the url is being opened on actual click event. This will work provided user has appropriate settings in the browser.
<a class="link">Link</a>
<script type="text/javascript">
$("a.link").on("click",function(){
window.open('www.yourdomain.com','_blank');
});
</script>
Similarly, if you are trying to do an ajax call within the click function and want to open a window on success, ensure you are doing the ajax call with async : false option set.
I think its not html target properties problem but you unchecked "open nw windows in a new tab instead" option in "tab" tab under firefox "options" menu. check it and try again.
I had this same question but found a relatively simple solution to it.
In JavaScript I was checking for window.opener !=null; to determine if the window was a pop up. If you're using some similar detection code to determine if the window you're site is being rendered in is a pop up you can easily "turn it off" when you want to open a "new" window using the new windows JavaScript.
Just put this at the top of your page you want to always be a "new" window.
<script type="text/javascript">
window.opener=null;
</script>
I use this on the log in page of my site so users don't get pop up behavior if they use a pop up window to navigate to my site.
You could even create a simple redirect page that does this and then moves to the URL you gave it. Something like,
JavaScript on parent page:
window.open("MyRedirect.html?URL="+URL, "_blank");
And then by using a little javascript from here you can get the URL and redirect to it.
JavaScript on Redirect Page:
<script type="text/javascript">
window.opener=null;
function getSearchParameters() {
var prmstr = window.location.search.substr(1);
return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}
function transformToAssocArray( prmstr ) {
var params = {};
var prmarr = prmstr.split("&");
for ( var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
var params = getSearchParameters();
window.location = params.URL;
</script>

Categories

Resources