Javascript window.open strange behavior in Firefox - javascript

I have a few links that should all open in the same window or tab.
To accomplish this I've given the window a name like in this example code:
<a href="#" onClick='window.open("http://somesite.com", "mywindow", "");'>link 1</a>
<a href="#" onClick='window.open("http://someothersite.com", "mywindow", "");'>link 2</a>
This works OK in internet explorer, but firefox always opens a new tab/window.
Any ideas?

Actually, the W3Schools documentation linked to by gabriel1836 is only a very very brief summary of functions.
And Oddly, mozilla's own developer reference CONTRADITCS this logic.
MDC / DOM / Window.open
var WindowObjectReference = window.open(strUrl,
strWindowName [, strWindowFeatures]);
If a window with the name
strWindowName already exists, then,
instead of opening a new window,
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. If you want to
open a new window on every call of
window.open(), you should use the
special value _blank for
strWindowName.
However, the page also states that there are many extensions that can be installed that change this behaviour.
So either the documentation mozilla provides for people targeting their own browser is wrong or something is odd with your test system :)
Also, your current A-Href notation is bad for the web, and will infuriate users.
<a href="http://google.com"
onclick="window.open( this.href, 'windowName' ); return false" >
Text
</a>
Is a SUBSTANTIALLY better way to do it.
Many people will instinctively 'middle click' links they want to manually open in a new tab, and having your only href as "#" infuriates them to depravity.
The "#" trick is a redundant and somewhat bad trick to stop the page going somewhere unintended, but this is only because of the lack of understanding of how to use onclick
If you return FALSE from an on-click event, it will cancel the links default action ( the default action being navigating the current page away )
Even better than this notation would be to use unintrusive javascript like so:
<a href="google.com" rel="external" >Text</a>
and later
<script type="text/javascript">
jQuery(function($){
$("a[rel*=external]").click(function(){
window.open(this.href, 'newWindowName' );
return false;
});
});
</script>

The window.open() function in Javascript is specifically designed to open a new window, please see: w3schools documentation. It actually sounds like IE is handling things in a non-standard way (which is hardly surprising).
If you want to relocate the existing location to a new page using Javascript, you should look at the location.replace() function.
Generally speaking I would recommend that you develop for Firefox and then fix for IE. Not only does Firefox offer better development tools but its implementation of W3C standards tends to be more correct.

By default FF uses a new tab if dimensions are omitted on the window.open parameters. You need to add dimensions for a new browser window.
Try this:
<a href="#" onClick='window.open("http://somesite.com", "mywindow", "width=700", "height=500");'>link 1</a>

Why don't you just use plain HTML like
Link
instead of using JavaScript?

Related

Open link in new window without window.opener reference

I'm having some issues with the window system in Javascript:
I have a website A that lists links to a different website B (currently <a> tags with target="_blank" attributes).
I would like the link in A to open in a new tab from B, however the page from B (which I cannot edit) contains a script that changes the location of the window.parent, in this case the tab containing the website A, then closes itself.
So I'm looking for a way to open a new tab/window without a reference to the current page in window.{parent/top/opener}. Is it possible ?
I found a way to remove the window.opener reference to my site, so if anyone encounters the same kind of problem here is a solution:
Link
var openLink = function(url) {
var w = window.open(url, '_blank');
w.opener = null;
}
Add the rel="noopener" attribute to the anchor tag:
<a target="_blank" rel="noopener" href="http://example.com">Link</a>
This is supported in most browsers: https://caniuse.com/#search=noopener
Notes:
IE and Edge don't support rel="noopener", but they also don't set window.opener for cross-origin links (I can't find an authoritative reference for this, however).
If you need to support other browsers (i.e. Safari 10 or others) that do set window.opener and don't support rel="noopener", #Elassyo's technique will work.

Javascript Window.Open Opens the Target URL in Both a New Window and the Same

Basically, I have a page with social media share buttons. Some of them work as they should (they open up in a new window), however, others open up both in a new window and in the same window. I have been going crazy for a day now over this and I cannot seem to find a way to fix it.
For reference, this is the page: http://www.inetsolutions.org/gsa-search-engine-ranker-ultimate-tutorial-and-genuine-review-seo-software-of-the-gods/
Link that works as expected (Facebook, Twitter, Pinterest):
<a href="javascript:void(0)" class="ism_link" onclick="indeedPinterestPopUp(2513);ism_fake_increment('.pinterest_share_count', 'pinterest', 'http://www.inetsolutions.org/gsa-search-engine-ranker-ultimate-tutorial-and-genuine-review-seo-software-of-the-gods/');">
Link that opens the URL to share in both a new window and in the same:
<a href="http://www.stumbleupon.com/badge/?url=http://www.inetsolutions.org/gsa-search-engine-ranker-ultimate-tutorial-and-genuine-review-seo-software-of-the-gods/&title=GSA%20Search%20Engine%20Ranker%20Ultimate%20Tutorial%20and%20Genuine%20Review%20%E2%80%93%20SEO%20Software%20of%20the%20Gods" class="ism_link" onclick="ism_fake_increment('.stumbleupon_share_count', 'stumbleupon', 'http://www.inetsolutions.org/gsa-search-engine-ranker-ultimate-tutorial-and-genuine-review-seo-software-of-the-gods/');return !window.open(this.href, '', 'width=700,height=575');">
What I have tried:
I have tried to remove the "href" attribute of the tag and insert the URL string into the window.open function instead of using "this.href". When I do that, the link opens only a new window, but doesn't open the share page of the respective social media, but rather, the target URL.
I have tried to add "return false" after the non-working window.open function.
I have also tried to remove the "ism_fake_increment" function just to test, but again, to no avail.
I have contacted the plugin author, but they requested to access my website internally, which is not going to happen.
Any ideas will be strongly appreciated. Thank you for your time!
I advise that you don't use the onclick attribute because it leads to extremely messy code. Instead, use the .addEventListener() in the DOM.
To disable the link from opening the link in the same window, just disable the default even. This can be done with .addEventListener() in the callback by calling the .preventDefault() method of the object passed into the callback:
//Get our link:
var link = document.getElementById("stumbleupon");
//Bind the click event:
link.addEventListener("click", function(event) {
//Prevent the link from opening regularly with .preventDefault():
event.preventDefault();
//The following code with the plugin does not work because we haven't included the plugin in the code snippet, but as you can clearly see if you click the link, the link has clearly been disabled because of the above call to .preventDefault().
//Do different stuff with the plugin:
ism_fake_increment('.stumbleupon_share_count', 'stumbleupon', 'http://www.inetsolutions.org/gsa-search-engine-ranker-ultimate-tutorial-and-genuine-review-seo-software-of-the-gods/');
return !window.open(this.href, '', 'width=700,height=575');
});
<!-- Set the ID attribute so we can find this link in the DOM: -->
<a id="stumbleupon" href="http://www.stumbleupon.com/badge/?url=http://www.inetsolutions.org/gsa-search-engine-ranker-ultimate-tutorial-and-genuine-review-seo-software-of-the-gods/&title=GSA%20Search%20Engine%20Ranker%20Ultimate%20Tutorial%20and%20Genuine%20Review%20%E2%80%93%20SEO%20Software%20of%20the%20Gods" class="ism_link">Hello! This is a link to stumbleupon.com!</a>

Basic Javascript question: How to open a new window?

How do I open a new window in javascript properly?
I've tried:
<a href='javascript:window.open("testing.html","mywindow","menubar=0,resizable=1,width=200,height=500,left=0,top=0");' >New Window</a>
This causes a new window to pop up but in Firefox it leaves the original page with a blank window saying "[object Window]". I've also had issues with IE as well.
How can I open a window that works in Firefox, IE, Safari and Chrome?
Bonus: If you can help in creating a link that is javascript degradable (I think that's the term).
By putting the script in the href property, the link will follow the string representation of the return value of the script.
The most backwards compatible way is to put the url and target in the link as regular attributes, and use the onclick event to open a window instead of following the link. By returning false from the event you prevent the link from being followed:
New Window
If Javascript is disabled in the browser, it will follow the link instead and open it in a new window.
Use the target _blank to open a new window.
javascript: links are pretty old-school. Try it with an onclick attribute. And don't forget to return false in the onclick handler to prevent the main page from following the link too.
New Window
you could add void(0) to your javascript code which will prevent the browser from doing anything to the current window
<a href='javascript:window.open("testing.html","mywindow","menubar=0,resizable=1,width=200,height=500,left=0,top=0"); void(0)' >New Window</a>
<a href='javascript:(function(){window.open("testing.html","mywindow","menubar=0,resizable=1,width=200,height=500,left=0,top=0")}();' >New Window</a>
Or make it a function:
File
<script>window.onload = function(){
document.getElementsByTagName('a').onclick =
function(evt){ el = evt.target; if (el.className == 'popup'){
window.open(el.href,"mywindow","menubar=0,resizable=1,width=200,height=500,left=0,top=0");
return false; }; };</script>

javascript popup issue In Internet Explorer !

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

What's the best way to open new browser window?

I know that most links should be left up to the end-user to decide how to open, but we can't deny that there are times you almost 'have to' force into a new window (for example to maintain data in a form on the current page).
What I'd like to know is what the consensus is on the 'best' way to open a link in a new browser window.
I know that <a href="url" target="_blank"> is out. I also know that <a href="#" onclick="window.open(url);"> isn't ideal for a variety of reasons. I've also tried to completely replace anchors with something like <span onclick="window.open(url);"> and then style the SPAN to look like a link.
One solution I'm leaning towards is <a href="url" rel="external"> and using JavaScript to set all targets to '_blank' on those anchors marked 'external'.
Are there any other ideas? What's better? I'm looking for the most XHTML-compliant and easiest way to do this.
UPDATE: I say target="_blank" is a no no, because I've read in several places that the target attribute is going to be phased out of XHTML.
I am using the last method you proposed. I add rel="external" or something similar and then use jQuery to iterate through all links and assign them a click handler:
$(document).ready(function() {
$('a[rel*=external]').click(function(){
window.open($(this).attr('href'));
return false;
});
});
I find this the best method because:
it is very clear semantically: you have a link to an external resource
it is standards-compliant
it degrades gracefully (you have a very simple link with regular href attribute)
it still allows user to middle-click the link and open it in new tab if they wish
Why is target="_blank" a bad idea?
It's supposed to do exactly what you want.
edit: (see comments) point taken, but I do think that using javascript to do such a task can lead to having some people quite upset (those who middle click to open on a new window by habit, and those who use a NoScript extension)
Please, don't force opening a link in a new window.
Reasons against it:
It infringes the rule of the least astonishment.
The back-button don't work and the user not possibly knows why.
What happen in tabbed browsers? New tab or new window? And whichever happens, is it what you wants, if you mix tabs and windows?
The reason I always hear in favor of opening a new window is that the user will not leave the site. But be sure, I will never come back to a site that annoys me. And if the site takes away control from me, that is a big annoyance.
A way may be, that you give two links, one is normal, the other opens it in a new window. Add the second with a little symbol after the normal link. This way users of your site stay in control of which link they want to click on.
Here is a plugin I wrote for jQuery
(function($){
$.fn.newWindow = function(options) {
var defaults = {
titleText: 'Link opens in a new window'
};
options = $.extend(defaults, options);
return this.each(function() {
var obj = $(this);
if (options.titleText) {
if (obj.attr('title')) {
var newTitle = obj.attr('title') + ' ('
+ options.titleText + ')';
} else {
var newTitle = options.titleText;
};
obj.attr('title', newTitle);
};
obj.click(function(event) {
event.preventDefault();
var newBlankWindow = window.open(obj.attr('href'), '_blank');
newBlankWindow.focus();
});
});
};
})(jQuery);
Example Usage
$('a[rel=external]').newWindow();
You can also change, or remove the title text, by passing in some options
Example to change title text:
$('a[rel=external]').newWindow( { titleText: 'This is a new window link!' } );
Example to remove it alltogether
$('a[rel=external]').newWindow( { titleText: '' } );
Perhaps I'm misunderstanding something but why don't you want to use target="_blank"? That's the way I would do it. If you're looking for the most compatible, then any sort of JavaScript would be out as you can't be sure that the client has JS enabled.
link text
Details are described in my answer to another question.
<a href="http://www.google.com" onclick="window.open(this.href); return false">
This will still open the link (albeit in the same window) if the user has JS disabled. Otherwise it works exactly like target=blank, and it's easy to use as you just have to append the onclick function (perhaps by using JQuery) to all normal tags.
If you use any flavor of strict doctype or the coming real xhtml-flavors, target isn't allowed ...
Using transitional, whatever being HTML4.01 or XHTML1, you can use Damirs solution, though it fails to implement the windowName-property which is necessary in window.open():
In plain html:
link
If however you use one of the strict doctypes your only way of opening links would be to use this solution without the target-attribute ...
-- by the way, the number of non-js-browsers is often miscalculated, looking up the counters numbers refer very different numbers, and I'm wondering how many of those non-js-browsers is crawlers and the like !-)
If I'm on a form page and clicking on a moreinfo.html link (for example) causes me to lose data unless I open it in a new tab/window, just tell me.
You can trick me in to opening a new tab/window with window.open() or target="_blank", but I might have targets and pop-ups disabled. If JS, targets and pop-ups are required for you to trick me into opening a new window/tab, tell me before I get started on the form.
Or, make links to another page a form request, so that when the visitor submits, the current form data is saved so they can continue from last time, if possible.
I use this...
$(function() {
$("a:not([href^='"+window.location.hostname+"'])").click(function(){
window.open(this.href);
return false;
}).attr("title", "Opens in a new window");
});

Categories