i have Problem with opening popups in javascript i have this function to open my popups in IE6 and IE7:
function open_window(Location,w,h) //opens new window
{
var win = "width="+w+",height="+h+",menubar=no,location=no,resizable,scrollbars,top=500,left=500";
alert(win) ;
window.open(Location,'newWin',win).focus();
}
it's working . i mean my new window opens but an error occurs. The Error Message is :
'window.open(...)' is null is not an object.
do you want to countinue running script on this page ?
then i have button in onclick event it's will call a function to close current window an refresh the opener function is
function refreshParent(location)
{
window.opener.location.href = location ;
window.close();
}
it's also gives me error : window.opener.location is null or not an object but i'm sure i'm passing correct parameters
i call it like this :
for second part :
<input type="button" name="pay" value="test" onclick="refreshParent('index.php?module=payment&task=default')" >
for first part :
<a onclick="javascript:open_window('?module=cart&task=add&id=<?=$res[xproductid]?>&popup=on','500' , '500')" style="cursor:pointer" id="addtocard"> <img src="../images/new_theme/buy_book.gif" width="123" border="0"/> </a>
it's really confuse me . Please Help ;)
When popup windows opened using window.open are blocked by a popup blocker, a feature of pretty much any modern browser these days, the return value of window.open() is not a window object, but null.
In order to circumvent these issues you would need to test the value returned by window.open() before attempting to invoke any methods on it.
Below is a piece of code to demonstrate how to go around this problem:
function open_window(Location,w,h) //opens new window
{
var options = "width=" + w + ",height=" + h;
options += ",menubar=no,location=no,resizable,scrollbars,top=500,left=500";
var newwin = window.open(Location,'newWin',options);
if (newwin == null)
{
// The popup got blocked, notify the user
return false;
}
newwin.focus();
}
In general, popup windows should be used only as a last resort or in controlled environments (internal company website, etc). Popup blockers tend to behave in very inconsistent ways and there may be more than a single popup blocker installed in a given browser so instructing the user on how to allow popups for a given website is not necessarily a solution. Example: IE7 + Google toolbar = two popup blockers.
If I may suggest, perhaps you should consider using something like this:
http://jqueryui.com/demos/dialog/
The advantages are numerous:
Skinnable, so you can create a more consistent look to match your website.
No popup blockers.
Good API and documentation that is consistent across most, if not all, major browsers.
If you still require that the newly opened "window" contain an external URL, you could use an IFRAME inside the opened dialog window.
Hope this helps,
Lior.
Works perfectly fine for me. Tested in IE6/7/8.
Of course I couldn't test it with your URLs so I replaced these with simple filenames. I'd suggest you try it also with simple filenames and see if it also fails then.
Beside that...
You don't need to add "javascript:" at the beginning of onclick attribute value.
It would also be good if you added a href="..." attribute to the link with the same URL that you give to open_window. Then it would become a real link and you wouldn't have to add cursor:pointer to it. For example:
<a href="?module=cart&task=add&id=<?=$res[xproductid]?>&popup=on"
onclick="open_window(this.href, '500' , '500'); return false;"> ...
Here is a way to have your cake and eat it too
I have not tested it on all browsers but it should really work
function open_window(url,target,w,h) { //opens new window
var parms = "width="+w+",height="+h+",menubar=no,location=no,resizable,scrollbars,top=500,left=500";
var win = window.open(url,target,parms);
if (win) {
win.focus();
return false; // cancel the onClick
}
return true; // make the link perform as normal
}
Using the link
<a href="?module=cart&task=add&id=<?=$res[xproductid]?>&popup=on"
target="newWin"
onclick="return open_window(this.href,this.target,500,500)"
id="addtocard"><img src="../images/new_theme/buy_book.gif" width="123" border="0"/></a>
which even saves you the silly cursor thing since it is an actual link which works even when JS is turned off
Related
If you open a window like:
window.open ("url","winName","location=0,width=300,height=214");
If winName is already open it just changes the URL in the window. This is ok but if that window is behind the current window most users won't realize this and think that it is just not opening.
Is there any way that if the window is already open, it brings it to the front?
Update: This hasn't worked since Chrome (21+). The workaround is to close/reopen.
The window.open() method returns an object that represents the new window. You just need to window.focus() it:
var w = window.open ("url","winName","location=0,width=300,height=214");
w.focus();
Or simply:
window.open("url","winName","location=0,width=300,height=214").focus();
The various answers suggesting using any form of .focus() are likely not going to work in all browsers.
This used to work back in the day but not any more, mainly due to browsers working to actively stop shady ad networks from pushing their popup ads to the foreground.
In Mozilla Firefox in particular (depending on your version) there is a configuration setting that is turned on by default that stops other windows (e.g. popups) from focusing themselves.
You can find this setting in the about:config page (tread carefully!)
dom.disable_window_flip: true
If I recall correctly this setting used to be called something like ~"allow_raise_or_lower_windows*
Other browsers may implement something similar, but quite simply if 1 of the major browsers blocks the use of .focus() by default then there's not much use in attempting to call it.
As a result, the only solution I've seen that works is to see if the window exists, and is not already closed... and if so close it, then load the window you want.
function closePopupIfOpen(popupName){
if(typeof(window[popupName]) != 'undefined' && !window[popupName].closed){
window[popupName].close();
}
}
when opening your popup if there's a chance it is already open (and burried behind other windows) then you can call this function before you attempt to open your popup.
closePopupIfOpen('fooWin');
var fooWin = window.open('someURL', 'foo', '...features...');
The drawback of course is that if there was anything "important" (e.g. a form partially filled in) in that window it will be lost.
Update: This hasn't worked since Chrome (21+). The workaround is to close/reopen.
Be careful, because when you open a new window, the opener window might still have some code to be executed, maybe some of this code gives it the focus. You would see how your new window opens in the front and suddenly goes to the back, so, it is a great idea in these cases, to set a timeout in order to give the focus to the new window a bit later on, when all the javascript in the opener window is executed, you can do it this way:
setTimeout(function(){window.focus();},1000);
Being 1000 the amount of miliseconds to wait, and window the name of the opened window.
You could also use this code in the opened window in the body onload for example.
I fixed this by adding
onclick="myWin = window.open('','winName','location=0,width=300,height=214'); myWin.focus()"
to the html element(button) and then change the URL via JS.
window.focus() applied to the window in question should do the trick.
You can use jQuery :
myPopup = window.open(url, "Title","menubar=no, status=no, scrollbars=no, menubar=no, width=800, height=800");
$(myPopup).focus();
Closing the window first, does the trick for me:
window.open('', 'mypopup').close();
setTimeout(function() {
window.open('', 'mypopup').focus();
}, 500);
I had the same problem, have spent a lot of time to find a solution, finally it works by this:
var singleWindow;
function openNewWindow(){
if(singleWindow){
singleWindow.close();
}
singleWindow = window.open ("url","winName","location=0,width=300,height=214");
}
This close the current window (if exist) and open a new window that will be placed on the top (default behavior)
Hope this help you !
I use window.open to populate a new window with varying content. Mostly reports and stored HTML from automated processes.
I have noticed some very inconsistent behavior with Chrome with respect to window.open().
Some of my calls will create a new tab (preferred behavior) and some cause popups.
var w = window.open('','_new');
w.document.write(page_content);
page_content is just regular HTML from AJAX calls. Reports contain some information in the header like title, favicon, and some style sheets.
In IE9 the code does cause a new tab instead of a pop-up, while Chrome flatly refuses to show the content in question in a new tab. Since the content is sensitive business data I cannot post it here. I'll answer questions if I can.
I know some people will say this is behavior left up to the user, but this is an internal business platform. We don't have time to train all the users on how to manage popups, and we just need it to be in a new tab. Heck, even a new window would be preferable to the popup since you cannot dock a popup in Chrome. Not to mention none of the popup blocking code would affect it.
Appreciate any insight.
window.open must be called within a callback which is triggered by a user action (example onclick) for the page to open in a new tab instead of a window.
Example:
$("a.runReport").click(function(evt) {
// open a popup within the click handler
// this should open in a new tab
var popup = window.open("about:blank", "myPopup");
//do some ajax calls
$.get("/run/the/report", function(result) {
// now write to the popup
popup.document.write(result.page_content);
// or change the location
// popup.location = 'someOtherPage.html';
});
});
You can try this:
open a new tab please
<script>
function openWindow(){
var w = window.open("about:blank");
w.document.write("heheh new page opened");
}
</script>
Is very easy, in order to force Chrome to open in a new tab, use the onmouseup event
onmouseup="switchMenu(event);"
I have tried this and it worked fine in chrome. If opening a new tab is on a user action(such as a mouse click) this will work fine without any issues. But if the code is executed in another script block, you may need to enable pop-ups in chrome. Looks like this is to handle all the click-bait sites.
let newTab = window.open('', '_blank');
if (this.viewerTab == null) {
console.log("opening in new tab to work, pop-ups should be enabled.");
return;
}
................
newTab.location.href = viewerUrl;
window.open('page.html', '_newtab');
Specify the '_newtab'. This works in IE and FF, and should work in Chrome. But if the user has things configured to not open in new tab then not much you can do.
As the title says "Google Chrome opens window.open(someurl) just fine...but page/window with clicked link also opens someurl.com.
When I click the "Click here" link with the onclick="shpop..." call attached, my pop up opens /facebook_login.php' correctly...BUT...at the same time, the original window opens /facebook_login.php too!
This happens in Chrome and IE, but FF is fine and doing just what i want..
I have this link:
Click here
I know I could remove the href="/facebook_login.php" and replace with href="#" .. but I need the link to work if js is disabled.
I have this js code imported in my tag:
function shpop(u,t,w,v)
{
var text = encodeURI(t);
var uri = encodeURI(u);
var h = document.location.href;
h = encodeURI(h);
var wwidth='600'; /*popup window width*/
var wheight='300'; /*popup window height*/
if(v=='' || undefined==v)v=document.domain; /*popup name/title */
switch(w){
case 'loginfb':
var url = '/facebook_login.php';
wwidth='980';
wheight='600';
break;
}
window.open(url,v,'width='+wwidth+',height='+wheight);
return false
}
Any ideas?
what is with returning false, and having false in the onclick?
This
onclick="shpop('','','loginfb','');return false"
Just needs to be
onclick="return shpop('','','loginfb','');"
If the onclick returns any error, the link will still open up. Do you see any errors in the JavaScript console? I wonder if the browsers are freaking out about any . in the window name from using document.domain. Try giving it a name.
onclick="return shpop('','','loginfb','foobar');"
According to the latest browser statistics - well last time it was measured anyway (2008) only 5% of users had Javascript disabled. Nowadays it's likely to be less. Consider that all browsers have it enabled by default. Therefore it's generally only advanced users that for whatever reason choose to disable javascript, and will therefore understand that there's a good chance any website they visit won't work as expected - Facebook, Google, Amazon - everyone uses javascript these days. It's perfectly acceptable to assume the user is using it, with one overall <noscript> version at the start of your page for those users if you really really want to cover all your bases :)
Here is the simplest solution:
<a href="/facebook_login.php"
target="FBpopup"
onclick="window.open('about:blank','FBpopup','width=980,height=600')">
Click here
</a>
You don't need return false because you actually want the link to execute.
The trick is to use the same window name in both the window.open and in the link target.
window.open will create the popup, then your login page will run in that popup.
If popups are blocked or Javascript is disabled, your login page will run in a new tab.
If you open a window like:
window.open ("url","winName","location=0,width=300,height=214");
If winName is already open it just changes the URL in the window. This is ok but if that window is behind the current window most users won't realize this and think that it is just not opening.
Is there any way that if the window is already open, it brings it to the front?
Update: This hasn't worked since Chrome (21+). The workaround is to close/reopen.
The window.open() method returns an object that represents the new window. You just need to window.focus() it:
var w = window.open ("url","winName","location=0,width=300,height=214");
w.focus();
Or simply:
window.open("url","winName","location=0,width=300,height=214").focus();
The various answers suggesting using any form of .focus() are likely not going to work in all browsers.
This used to work back in the day but not any more, mainly due to browsers working to actively stop shady ad networks from pushing their popup ads to the foreground.
In Mozilla Firefox in particular (depending on your version) there is a configuration setting that is turned on by default that stops other windows (e.g. popups) from focusing themselves.
You can find this setting in the about:config page (tread carefully!)
dom.disable_window_flip: true
If I recall correctly this setting used to be called something like ~"allow_raise_or_lower_windows*
Other browsers may implement something similar, but quite simply if 1 of the major browsers blocks the use of .focus() by default then there's not much use in attempting to call it.
As a result, the only solution I've seen that works is to see if the window exists, and is not already closed... and if so close it, then load the window you want.
function closePopupIfOpen(popupName){
if(typeof(window[popupName]) != 'undefined' && !window[popupName].closed){
window[popupName].close();
}
}
when opening your popup if there's a chance it is already open (and burried behind other windows) then you can call this function before you attempt to open your popup.
closePopupIfOpen('fooWin');
var fooWin = window.open('someURL', 'foo', '...features...');
The drawback of course is that if there was anything "important" (e.g. a form partially filled in) in that window it will be lost.
Update: This hasn't worked since Chrome (21+). The workaround is to close/reopen.
Be careful, because when you open a new window, the opener window might still have some code to be executed, maybe some of this code gives it the focus. You would see how your new window opens in the front and suddenly goes to the back, so, it is a great idea in these cases, to set a timeout in order to give the focus to the new window a bit later on, when all the javascript in the opener window is executed, you can do it this way:
setTimeout(function(){window.focus();},1000);
Being 1000 the amount of miliseconds to wait, and window the name of the opened window.
You could also use this code in the opened window in the body onload for example.
I fixed this by adding
onclick="myWin = window.open('','winName','location=0,width=300,height=214'); myWin.focus()"
to the html element(button) and then change the URL via JS.
window.focus() applied to the window in question should do the trick.
You can use jQuery :
myPopup = window.open(url, "Title","menubar=no, status=no, scrollbars=no, menubar=no, width=800, height=800");
$(myPopup).focus();
Closing the window first, does the trick for me:
window.open('', 'mypopup').close();
setTimeout(function() {
window.open('', 'mypopup').focus();
}, 500);
I had the same problem, have spent a lot of time to find a solution, finally it works by this:
var singleWindow;
function openNewWindow(){
if(singleWindow){
singleWindow.close();
}
singleWindow = window.open ("url","winName","location=0,width=300,height=214");
}
This close the current window (if exist) and open a new window that will be placed on the top (default behavior)
Hope this help you !
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');