Use this function:
var downloadURL = function(url)
{
var iframe;
iframe = document.getElementById("hiddenDownloader");
if (iframe === null)
{
iframe = document.createElement('iframe');
iframe.id = "hiddenDownloader";
iframe.style.visibility = 'hidden';
document.body.appendChild(iframe);
}
iframe.src = url;
}
The way it works is by creating an invisible iframe (only once) which can be then set to download files from the internet.
To force the browser to download a file it would otherwise be capable of rendering, you need the server to set the file's MIME Type to a nonsensical value, such as application/x-please-download-me
or alternatively application/octet-stream
, which is used for arbitrary binary data.
Edit: If you only want to open it in a new tab, the only way to do this is for the user to a click on a link with its target
attribute set to _blank
...
In jQuery:
$('a#someID').attr({target: '_blank',
href : 'http://localhost/blahblah/file.pdf'}).;
Whenever that link is clicked, it will download the file in a new tab/window.