JavaScript: location.href to open in new window/tab?
Asked Answered
M

7

508

I have a JavaScript file from a third party developer. It has a has link which replaces the current page with the target. I want to have this page opened in a new tab.

This is what I have so far:

if (command == 'lightbox') {
 location.href="https://support.wwf.org.uk/earth_hour/index.php?type=individual";
}

Can anyone help me out?

Medick answered 28/2, 2011 at 12:22 Comment(0)
H
1255
window.open(
  'https://support.wwf.org.uk/earth_hour/index.php?type=individual',
  '_blank' // <- This is what makes it open in a new window.
);
Hortatory answered 28/2, 2011 at 12:24 Comment(10)
Worth to mention: Whether a new tab or window is created, is decided by the browser (setting).Auklet
@Hortatory I edited this answer to make the important bit readable. If you don't approve of my formatting, may I suggest shortening the URL so that the second parameter fits within the unscrolling region?Pierette
Though late but useful, Someone asked if the '_blank' is default text or must be written that way or it does have any impact on the entire window.open (???)... Just for the records, the _blank can be textString. You could even write it as my_newWindow or whatever. Provided that: The is no blank spaces in between the characters also note that this is NOT going to be the title* of the new. window.Cabman
@Cabman That's incorrect. "_blank" guarantees that the window/tab will be new. Anything else (besides the other special names) are giving that window the specific name, and subsequent links to that target will reuse the window. jsFiddle.Hortatory
Not really. Just commented out the 'if` statement in your fiddle. Both buttons work like VOODOO!. Try it and VOILA! _random_string works as well as _blank. In fact one of theAdvantages of this method is that the user has brand NewWindows for different purposes i.e: my_SPORTS_Window, my_NEWS_Window,my_EMAIL_Window...etc, & when S/he clicks on a Link that deals withSports, it'll goDirectly to my_SPORTS_Window and open there. How cool is that?, Please read thisDO NOT use target="_blank" by MDN. developer.mozilla.org/en-US/docs/Web/API/…Cabman
@Cabman The if had nothing to do with it (it was used to ensure the clicks were from the button elements only). You're basically iterating what I mentioned in my comment.Hortatory
@Alex.. I get your point bro. However, The If disables the use of other custom strings. Uncomment it and try something like myNewTab, or my_NewTab or myNewTab_... --The button goes dormant--. The reason why I mentioned you should remove the if is that the if obliges strings to start with an _ (underscore) as in, it being the first char of the string. //Removing it === BOOM! any string will open a brand new Tab or Window depending on the browsers' specifics and the window can be reused severally if necessary... If that's what you also mean, then we are on the same boat.Cabman
What is type=individual? Neither this nor the _blank part are necessary (any more). The window.open command opens a new browser window or tab by default.Averil
This just triggers a pop up block notification in modern browsers, doesn't simulate a _blank anchor click at all.Verdha
popup prevented by browser.Baecher
N
51

Pure js alternative to window.open

let a= document.createElement('a');
a.target= '_blank';
a.href= 'https://support.wwf.org.uk/';
a.click();

here is working example (stackoverflow snippets not allow to opening)

Nutt answered 5/12, 2019 at 19:2 Comment(5)
Triggers Chrome's built-in popup blocker in the latest Chrome here on Jan 4, 2022.Unpleasant
@Unpleasant In my chrome version is 96.0.4664.110 (Official Build) (arm64) (MacOs) - example works. What is you chrome version?Sexdecillion
I am on Windows 10. Version 96.0.4664.110 (Official Build) (64-bit). When I click your example hyperlink, Chrome intercepts and blocks the popup and I get an alert on my address bar. screencast.com/t/b6wA1VayUnpleasant
Perhaps you enabled popups from jsfiddle.net. That might be why you don't see the popup blocking.Unpleasant
This solution is better than window.open since it can work in safariTrover
S
39

If you want to use location.href to avoid popup problems, you can use an empty <a> ref and then use javascript to click it.

something like in HTML

<a id="anchorID" href="mynewurl" target="_blank"></a>

Then javascript click it as follows

document.getElementById("anchorID").click();
Skilling answered 15/8, 2014 at 14:50 Comment(8)
I was hopeful for this solution, however it does still seem to trigger the pop-up block (at least in Chrome). I have a feeling that the browser is aware that it's a javascript click and treats it differently.Verdha
Thank you Nathan. You're quite correct. You still get a pop up block message. I thought I'd cured it. In theory it should have worked. AndrewSkilling
$("#anchorID")[0].click(); to use this solution with jquery.Hardiman
Lol theBell, It's not jQuery if you are accessing directly DOM Element [0]Egg
This is the best solution. Works in safari too.Heritable
This solves my problem, thanks.Enrobe
This is the perfect solution. Works in all browsers without blocking.Leopold
Safari blocks this solution.Provinciality
Y
13

You can open it in a new window with window.open('https://support.wwf.org.uk/earth_hour/index.php?type=individual');. If you want to open it in new tab open the current page in two tabs and then alllow the script to run so that both current page and the new page will be obtained.

Yarmouth answered 28/2, 2011 at 12:28 Comment(1)
Triggers Chrome built-in popup blocker.Unpleasant
H
11

usage of location.href will replace current url with new url i.e link in the same webpage.

To open a new tab you can use as below:

if (command == 'lightbox') {
 window.open("https://support.wwf.org.uk/earth_hour/index.php?type=individual", '_blank');
}
Hazelhazelnut answered 8/6, 2021 at 6:36 Comment(0)
A
1

For example:

    $(document).on('click','span.external-link',function(){
        var t               = $(this), 
            URL             = t.attr('data-href');        
        $('<a href="'+ URL +'" target="_blank">External Link</a>')[0].click();

    });

Working example.

Autobahn answered 13/5, 2018 at 13:34 Comment(2)
Popup prevented by browser.Jerboa
It means that you either have an adblock or something else that blocks it. The default behaviour should be working under normal conditionsWellmeaning
C
0

You can also open a new tab calling to an action method with parameter like this:

   var reportDate = $("#inputDateId").val();
   var url = '@Url.Action("PrintIndex", "Callers", new {dateRequested = "findme"})';
   window.open(window.location.href = url.replace('findme', reportDate), '_blank');
Clifton answered 4/6, 2020 at 20:32 Comment(2)
Are the first and second line required? Won't it work without the reportDate and url variables?Burkhart
You can take out the parameter (reportDate), but the url var is important because it contains the call to the action method.Clifton

© 2022 - 2024 — McMap. All rights reserved.