I have a Base64 encoded document which can be PDF file or image.
I would like to create a button in HTML5 page that opens this base64 in a new tab (or new page it does not matter)
I found this code can do the trick :
<a href="http://chriscoyier.net"
onclick="window.open(this.href); return false;"
onkeypress="window.open(this.href); return false;">
This link will open in new window/tab
</a>
It works well.
But when I replace the http link with
href="data:application/octet-stream;base64,/9j/4A.."
then the file is downloaded but not displayed in browser.
Your MIME type is set to 'application/octet-stream', which will generally be downloaded and not displayed (depending on browser and system settings). If you are trying to load browser-displayable content, then you should use a more appropriate MIME type for your content so that it displays inline and does not get downloaded.
Please note: As of Chrome 60 and an upcoming version of FireFox (although it appears FireFox will still support images), data URIs cannot be opened in the top-level frame of the browser (and it was never supported in IE/Edge), but they can be opened in iframes and img elements.
The workaround below is tested and working in the latest version of the above browsers. This could also be rewritten with an img tag to display an image.
<button id='btnDownload'>Download</button>
document.getElementById('btnDownload').addEventListener('click', function(){
var w = window.open('about:blank');
setTimeout(function(){ //FireFox seems to require a setTimeout for this to work.
w.document.body.appendChild(w.document.createElement('iframe'))
.src = 'data:application/octet-stream;base64,SWYgSSBoYWQgYSBuaWNrbGUgZm9yIGV2ZXJ5IHRpbWUgSSBoYWQgYSBuaWNrbGUsIEknZCBoYXZlIGVhdGVuIHR3aWNlIGFzIG1hbnkgcGlja2xlcy4=';
}, 0);
});
If, however, your intention is to just download the content (contrary to the stated intent in the question, but applicable to 'application/octet-stream' content in general), this should suffice:
<a href='data:application/octet-stream;base64,SWYgSSBoYWQgYSBuaWNrbGUgZm9yIGV2ZXJ5IHRpbWUgSSBoYWQgYSBuaWNrbGUsIEknZCBoYXZlIGVhdGVuIHR3aWNlIGFzIG1hbnkgcGlja2xlcy4=' download>Download this</a>
Tested on chrome and Firefox, just add the base64 value into the href attribute works (without onclick & onkeypress events). Just like that :
<html>
<body>
test
</body>
</html>
I am adding the answer to my question based on Aaron's answer:
document.getElementById('btnDownload').addEventListener('click', function(){
var w = window.open('about:blank');
setTimeout(function(){ //FireFox seems to require a setTimeout for this to
work.
w.document.body.appendChild(w.document.createElement('iframe'))
.src = $this.attr('href');
w.document.getElementsByTagName("iframe")[0].style.width = '100%';
w.document.getElementsByTagName("iframe")[0].style.height = '100%';
}, 0);
});
<a href="aHR0cHM6Ly93d3cuc3dpdGNoLXRvcnJlbnRzLmNvbS9kb3dubG9hZC80MTMvU3VwZXIlMjBTbWFzaCUyMEJyb3MlMjBVbHRpbWF0ZS50b3JyZW50"
onclick="window.open(this.href); return false;"
onkeypress="window.open(this.href); return false;">
This link will open in new window/tab
</a>
Related
I've build a web page that let's you select a page name from a drop down list and then transfers the browser to that page. The code that does the transfer is
if (url){
window.open(url, '_blank');
}
where "url" is the page selected.
A console log just before the window.open line prints something like:
executing: window.open(http://www.mywebsite.com/44/threats.html, '_blank')
and then the browsers opens the page in a new tab.
This works fine on Windows 7 for all the browsers, including Safari.
On an iMac it works for Firefox but not for Safari.
Does anyone know why iMac/Safari won't do this?
Safari is blocking any call to window.open() which is made inside an async call.
The solution that I found to this problem is to call window.open before making an asnyc call and set the location when the promise resolves.
var windowReference = window.open();
myService.getUrl().then(function(url) {
windowReference.location = url;
});
Using setTimeout
Wrapping your window.open(url, '_blank') line of code in the async function with a setTimeout works as well,
setTimeout(() => {
window.open(url, '_blank');
})
setTimeout code runs on the main thread, instead of the asynchronous one.
Tested in Chrome and Safari.
To use window.open() in safari you must put it in an element's onclick event attribute.
For example:
<button class='btn' onclick='window.open("https://www.google.com", "_blank");'>Open Google search</button>
You can't rely on window.open because browsers may have different policies. I had the same issue and I used the code below instead.
let a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = <your_url>;
a.download = <your_fileName>;
a.click();
document.body.removeChild(a);
Taken from the accepted answers comment by Steve on Dec 20, 2013:
Actually, there's a very easy way to do it: just click off "Block popup windows" in the iMac/Safari browser and it does what I want.
To clarify, when running Safari on Mac OS X El Capitan:
Safari -> Preferences
Security -> Uncheck 'Block pop-up windows'
window.location.assign(url) this fixs the window.open(url) issue in ios devices
Open link in a new tab, programatically with JavaScript for: safari, mobile safari and other browsers:
const link = 'https://google.com';
const a = document.createElement("a");
a.setAttribute('href', link);
a.setAttribute('target', '_blank');
a.click();
There's a setting in Safari under "Tabs" that labeled Open pages in tabs instead of windows: with a drop down with a few options. I'm thinking yours may be set to Always. Bottom line is you can't rely on a browser opening a new window.
This should work: window.location.assign(url);
Usually it is important to save the state, before leaving the page, so have this in mind as well.
The correct syntax is window.open(URL,WindowTitle,'_blank') All the arguments in the open must be strings. They are not mandatory, and window can be dropped. So just newWin=open() works as well, if you plan to populate newWin.document by yourself.
BUT you MUST use all the three arguments, and the third one set to '_blank' for opening a new true window and not a tab.
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.
I've build a web page that let's you select a page name from a drop down list and then transfers the browser to that page. The code that does the transfer is
if (url){
window.open(url, '_blank');
}
where "url" is the page selected.
A console log just before the window.open line prints something like:
executing: window.open(http://www.mywebsite.com/44/threats.html, '_blank')
and then the browsers opens the page in a new tab.
This works fine on Windows 7 for all the browsers, including Safari.
On an iMac it works for Firefox but not for Safari.
Does anyone know why iMac/Safari won't do this?
Safari is blocking any call to window.open() which is made inside an async call.
The solution that I found to this problem is to call window.open before making an asnyc call and set the location when the promise resolves.
var windowReference = window.open();
myService.getUrl().then(function(url) {
windowReference.location = url;
});
Using setTimeout
Wrapping your window.open(url, '_blank') line of code in the async function with a setTimeout works as well,
setTimeout(() => {
window.open(url, '_blank');
})
setTimeout code runs on the main thread, instead of the asynchronous one.
Tested in Chrome and Safari.
To use window.open() in safari you must put it in an element's onclick event attribute.
For example:
<button class='btn' onclick='window.open("https://www.google.com", "_blank");'>Open Google search</button>
You can't rely on window.open because browsers may have different policies. I had the same issue and I used the code below instead.
let a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = <your_url>;
a.download = <your_fileName>;
a.click();
document.body.removeChild(a);
Taken from the accepted answers comment by Steve on Dec 20, 2013:
Actually, there's a very easy way to do it: just click off "Block popup windows" in the iMac/Safari browser and it does what I want.
To clarify, when running Safari on Mac OS X El Capitan:
Safari -> Preferences
Security -> Uncheck 'Block pop-up windows'
window.location.assign(url) this fixs the window.open(url) issue in ios devices
Open link in a new tab, programatically with JavaScript for: safari, mobile safari and other browsers:
const link = 'https://google.com';
const a = document.createElement("a");
a.setAttribute('href', link);
a.setAttribute('target', '_blank');
a.click();
There's a setting in Safari under "Tabs" that labeled Open pages in tabs instead of windows: with a drop down with a few options. I'm thinking yours may be set to Always. Bottom line is you can't rely on a browser opening a new window.
This should work: window.location.assign(url);
Usually it is important to save the state, before leaving the page, so have this in mind as well.
The correct syntax is window.open(URL,WindowTitle,'_blank') All the arguments in the open must be strings. They are not mandatory, and window can be dropped. So just newWin=open() works as well, if you plan to populate newWin.document by yourself.
BUT you MUST use all the three arguments, and the third one set to '_blank' for opening a new true window and not a tab.
I'm trying to set the src of an iframe to "view-source: {URL}" using the following:
var url = document.getElementById('url');
var submit = document.getElementById('submit');
var target = document.getElementById('target');
submit.onclick = function(){
window.frames['target'].location.href = "view-source:" + url.value;
};
But it seems to set the src of the iframe relative to my website where the iframe is. I suppose because "view-source: x" only works when implemented with "location.href"?
Is this the case?
I'm using JS by the way!
Html:
<input type="text" id="url"></input>
<button id="submit">Submit</button>
<iframe id="target" src=""></iframe>
This is pretty interesting.
There must be some kind of restriction on "view-source" URLs in windows that already exist, because opening a new window via window.open works, but opening an existing window (that happens to be an iframe) with the "view-source" URL doesn't work, and opening the URL in a top level window that is already present also doesn't work (try the last example twice with different URLs, it will only work the first time).
view-source is probably best treated as browser black magic voodoo and not as a regular URI scheme.
All of this was tested in Chrome, by the way. The rules may be different for other browsers supporting "view-source."
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