[javascript] How to use target in location.href

I am currently developing a web application where I need to open a popup window to show a report. The problem is that some versions of explorer don't support the window.open javascript function, so when this is the case I catch the error and open the new url with location.href. Here the code:

try {
    window.open(url, "","width=1002,height=700,location=0,menubar=0,scrollbars=1,status=1,resizable=0")
} catch(e) {
    location.target = "_blank";
    location.href = url;
}

The problem is that the location.target is not working and I would like to know if there is a way to specify the target of the location.href so it can be opened in a new tab.

This question is related to javascript window.open

The answer is


As of 2014, you can trigger the click on a <a/> tag. However, for security reasons, you have to do it in a click event handler, or the browser will tag it as a popup (some other events may allow you to safely trigger the opening).

jsFiddle


You could try this:

        <script type="text/javascript">
         function newWindow(url){
                window.open(url);
            }
        </script>

And call the function


If you go with the solution by @qiao, perhaps you would want to remove the appended child since the tab remains open and subsequent clicks would add more elements to the DOM.

// Code by @qiao
var a = document.createElement('a')
a.href = 'http://www.google.com'
a.target = '_blank'
document.body.appendChild(a)
a.click()
// Added code
document.body.removeChild(a)

Maybe someone could post a comment to his post, because I cannot.


Why not have a hidden anchor tag on the page with the target set as you need, then simulate clicking it when you need the pop out?

How can I simulate a click to an anchor tag?

This would work in the cases where the window.open did not work


try this one, which simulates a click on an anchor.

var a = document.createElement('a');
a.href='http://www.google.com';
a.target = '_blank';
document.body.appendChild(a);
a.click();

You can use this on any element where onclick works:

onclick="window.open('some.htm','_blank');"


<a href="url" target="_blank"> <input type="button" value="fake button" /> </a>

If you are using an <a/> to trigger the report, you can try this approach. Instead of attempting to spawn a new window when window.open() fails, make the default scenario to open a new window via target (and prevent it if window.open() succeeds).

HTML

<a href="http://my/url" target="_blank" id="myLink">Link</a>

JS

var spawn = function (e) {
    try {
        window.open(this.href, "","width=1002,height=700,location=0,menubar=0,scrollbars=1,status=1,resizable=0")
        e.preventDefault(); // Or: return false;
    } catch(e) {
    // Allow the default event handler to take place
    }
}

document.getElementById("myLink").onclick = spawn;