Is there a polyfill for link download with data uri? - javascript

I have some code should be generated by the server:
<a download="test.csv" href="data:text/plain;charset=utf-8;base64,w4FydsOtenTFsXLFkXTDvGvDtnJmw7p0w7Nnw6lwLg==">
teszt
</a>
It works with current chrome, firefox, opera. I'd like it to support MSIE11. Afaik msSaveBlob is the solution for that. Is there an existing js polyfill I could use, or should I write it?

Okay I made a simple polyfill based on the code I found in SO answers and here. I tested it on MSIE11, it works. It does not support file download with XHR, just data URIs. I recommend to use the Content-Disposition response header instead if you want to force file download. In my case the server just creates the file, but should not store it and I needed a HTML response as well, so this was the way to go. An alternative solution would be to send the file in email, but I found this one better by small files.
(function (){
addEvent(window, "load", function (){
if (isInternetExplorer())
polyfillDataUriDownload();
});
function polyfillDataUriDownload(){
var links = document.querySelectorAll('a[download], area[download]');
for (var index = 0, length = links.length; index<length; ++index) {
(function (link){
var dataUri = link.getAttribute("href");
var fileName = link.getAttribute("download");
if (dataUri.slice(0,5) != "data:")
throw new Error("The XHR part is not implemented here.");
addEvent(link, "click", function (event){
cancelEvent(event);
try {
var dataBlob = dataUriToBlob(dataUri);
forceBlobDownload(dataBlob, fileName);
} catch (e) {
alert(e)
}
});
})(links[index]);
}
}
function forceBlobDownload(dataBlob, fileName){
window.navigator.msSaveBlob(dataBlob, fileName);
}
function dataUriToBlob(dataUri) {
if (!(/base64/).test(dataUri))
throw new Error("Supports only base64 encoding.");
var parts = dataUri.split(/[:;,]/),
type = parts[1],
binData = atob(parts.pop()),
mx = binData.length,
uiArr = new Uint8Array(mx);
for(var i = 0; i<mx; ++i)
uiArr[i] = binData.charCodeAt(i);
return new Blob([uiArr], {type: type});
}
function addEvent(subject, type, listener){
if (window.addEventListener)
subject.addEventListener(type, listener, false);
else if (window.attachEvent)
subject.attachEvent("on" + type, listener);
}
function cancelEvent(event){
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
function isInternetExplorer(){
return /*#cc_on!#*/false || !!document.documentMode;
}
})();

Related

Javascript inline script onchange not working

i'm having a problem on making my code to adjust to my web server, because of the security purposes, all inline javascript code to my html is not allowed.
everything is already okay i'm just having a hard time converting my other code to pure javascript
Here is my existing code,,,
<label class=qrcode-text-btn><input type=file accept="image/*" capture=environment id="openQRCamera" tabindex=-1></label>
the original code is this
<label class=qrcode-text-btn><input type=file accept="image/*" capture=environment onchange="openQRCamera(this);" tabindex=-1></label>
the onchange is not working because it is inline in the html.
this function needs to open a camera and detect if there is a qr that exists.
here is what i have now on converting it.
document.querySelector("#openQRCamera").addEventListener('onchange', (node) => {
var reader = new FileReader();
reader.onload = function() {
node.value = "";
qrcode.callback = function(res) {
if(res instanceof Error) {
alert("There is no QR detected");
} else {
node.parentNode.previousElementSibling.value = res;
}
};
qrcode.decode(reader.result);
};
reader.readAsDataURL(node.files[0]);
});
here is the original code
function openQRCamera(node) {
var reader = new FileReader();
reader.onload = function() {
node.value = "";
qrcode.callback = function(res) {
if(res instanceof Error) {
alert("There is no QR detected");
} else {
node.parentNode.previousElementSibling.value = res;
}
};
qrcode.decode(reader.result);
};
reader.readAsDataURL(node.files[0]);
}
i am using this website as my source of code, everything is working fine in my localhost, but the server is just strict, and i think that's normal for all the websites.
https://www.sitepoint.com/create-qr-code-reader-mobile-website/
i just been stuck and try to do other solution like adding event listener, and append of input just by using jquery, but it's not working. thanks in advance.
The event listener you are using is faulty, instead of listenning to 'onchange' you have to listen to 'change' like so:
document.querySelector("#openQRCamera").addEventListener('change', () => {
//remove the node as parameter and get it with javascript:
var node = document.getElementById('openQRCamera');
..

Generate a download on button click [duplicate]

I want to force the browser to download a pdf file.
I am using the following code :
<a href="../doc/quot.pdf" target=_blank>Click here to Download quotation</a>
It makes the browser open the pdf in a new window, but I want it to download to the hard drive when a user clicks it.
I found that Content-disposition is used for this, but how do I use it in my case?
On the HTTP Response where you are returning the PDF file, ensure the content disposition header looks like:
Content-Disposition: attachment; filename=quot.pdf;
See content-disposition on the wikipedia MIME page.
With recent browsers you can use the HTML5 download attribute as well:
<a download="quot.pdf" href="../doc/quot.pdf">Click here to Download quotation</a>
It is supported by most of the recent browsers except MSIE11. You can use a polyfill, something like this (note that this is for data uri only, but it is a good start):
(function (){
addEvent(window, "load", function (){
if (isInternetExplorer())
polyfillDataUriDownload();
});
function polyfillDataUriDownload(){
var links = document.querySelectorAll('a[download], area[download]');
for (var index = 0, length = links.length; index<length; ++index) {
(function (link){
var dataUri = link.getAttribute("href");
var fileName = link.getAttribute("download");
if (dataUri.slice(0,5) != "data:")
throw new Error("The XHR part is not implemented here.");
addEvent(link, "click", function (event){
cancelEvent(event);
try {
var dataBlob = dataUriToBlob(dataUri);
forceBlobDownload(dataBlob, fileName);
} catch (e) {
alert(e)
}
});
})(links[index]);
}
}
function forceBlobDownload(dataBlob, fileName){
window.navigator.msSaveBlob(dataBlob, fileName);
}
function dataUriToBlob(dataUri) {
if (!(/base64/).test(dataUri))
throw new Error("Supports only base64 encoding.");
var parts = dataUri.split(/[:;,]/),
type = parts[1],
binData = atob(parts.pop()),
mx = binData.length,
uiArr = new Uint8Array(mx);
for(var i = 0; i<mx; ++i)
uiArr[i] = binData.charCodeAt(i);
return new Blob([uiArr], {type: type});
}
function addEvent(subject, type, listener){
if (window.addEventListener)
subject.addEventListener(type, listener, false);
else if (window.attachEvent)
subject.attachEvent("on" + type, listener);
}
function cancelEvent(event){
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
function isInternetExplorer(){
return /*#cc_on!#*/false || !!document.documentMode;
}
})();

Alternative for Html Anchor tag `download` attribute which doesn't work in Internet Explorer [duplicate]

From the following code I'm creating a dynamic anchor tag which downloads a file. This code works well in Chrome but not in IE. How can I get this working
<div id="divContainer">
<h3>Sample title</h3>
</div>
<button onclick="clicker()">Click me</button>
<script type="text/javascript">
function clicker() {
var anchorTag = document.createElement('a');
anchorTag.href = "http://cdn1.dailymirror.lk/media/images/finance.jpg";
anchorTag.download = "download";
anchorTag.click();
var element = document.getElementById('divContainer');
element.appendChild(anchorTag);
}
</script>
Internet Explorer does not presently support the Download attribute on A tags.
See http://caniuse.com/download and http://status.modern.ie/adownloadattribute; the latter indicates that the feature is "Under consideration" for IE12.
In my case, since there's a requirement to support the usage of IE 11 (version 11.0.9600.18665), I ended up using the solution provided by #Henners on his comment:
// IE10+ : (has Blob, but not a[download] or URL)
if (navigator.msSaveBlob) {
return navigator.msSaveBlob(blob, fileName);
}
It's quite simple and practical.
Apparently, this solution was found on the Javascript download function created by dandavis.
Old question, but thought I'd add our solution. Here is the code I used on my last project. It's not perfect, but it passed QA in all browsers and IE9+.
downloadCSV(data,fileName){
var blob = new Blob([data], {type: "text/plain;charset=utf-8;"});
var anchor = angular.element('<a/>');
if (window.navigator.msSaveBlob) { // IE
window.navigator.msSaveOrOpenBlob(blob, fileName)
} else if (navigator.userAgent.search("Firefox") !== -1) { // Firefox
anchor.css({display: 'none'});
angular.element(document.body).append(anchor);
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(data),
target: '_blank',
download: fileName
})[0].click();
anchor.remove();
} else { // Chrome
anchor.attr({
href: URL.createObjectURL(blob),
target: '_blank',
download: fileName
})[0].click();
}
}
Using the ms specific API worked best for us in IE. Also note that some browsers require the anchor to actually be in the DOM for the download attribute to work, whereas Chrome, for example, does not. Also, we found some inconsistencies with how Blobs work in various browsers. Some browsers also have an export limit. This allows the largest possible CSV export in each browser afaik.
As of build 10547+, the Microsoft Edge browser is now supporting the download attribute on a tags.
Download Image
Edge features update: https://dev.windows.com/en-us/microsoft-edge/platform/changelog/desktop/10547/
a[download] standard: http://www.w3.org/html/wg/drafts/html/master/links.html#attr-hyperlink-download
This code fragment allows saving blob in the file in IE, Edge and other modern browsers.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
// Extract filename form response using regex
var filename = "";
var disposition = request.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
if (window.navigator.msSaveOrOpenBlob) { // for IE and Edge
window.navigator.msSaveBlob(request.response, filename);
} else {
// for modern browsers
var a = document.createElement('a');
a.href = window.URL.createObjectURL(request.response);
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
}
}
button.disabled = false;
dragArea.removeAttribute('spinner-visible');
// spinner.style.display = "none";
};
request.open("POST", "download");
request.responseType = 'blob';
request.send(formData);
For IE and Edge use: msSaveBlob
Use my function
It bind your atag to download file in IE
function MS_bindDownload(el) {
if(el === undefined){
throw Error('I need element parameter.');
}
if(el.href === ''){
throw Error('The element has no href value.');
}
var filename = el.getAttribute('download');
if (filename === null || filename === ''){
var tmp = el.href.split('/');
filename = tmp[tmp.length-1];
}
el.addEventListener('click', function (evt) {
evt.preventDefault();
var xhr = new XMLHttpRequest();
xhr.onloadstart = function () {
xhr.responseType = 'blob';
};
xhr.onload = function () {
navigator.msSaveOrOpenBlob(xhr.response, filename);
};
xhr.open("GET", el.href, true);
xhr.send();
})
}
Append child first and then click
Or you can use window.location= 'url' ;
As mentioned in earlier answer , download attribute is not supported in IE . As a work around, you can use iFrames to download the file . Here is a sample code snippet.
function downloadFile(url){
var oIframe = window.document.createElement('iframe');
var $body = jQuery(document.body);
var $oIframe = jQuery(oIframe).attr({
src: url,
style: 'display:none'
});
$body.append($oIframe);
}
I copied the code from here and updated it for ES6 and ESLint and added it to my project.
You can save the code to download.js and use it in your project like this:
import Download from './download'
Download('/somefile.png', 'somefile.png')
Note that it supports dataURLs (from canvas objects), and more... see https://github.com/rndme for details.

Make a link from Electron open in browser

Is there any (simple/built-in way) to open a new browser (I mean default OS browser) window for a link from Electron instead of visiting that link inside your Electron app ?
You can simply use :
require("shell").openExternal("http://www.google.com")
EDIT: #Arjun Kava's answer is much better these days.
This answer is quite old and assumes you have jQuery.
const shell = require('electron').shell;
// assuming $ is jQuery
$(document).on('click', 'a[href^="http"]', function(event) {
event.preventDefault();
shell.openExternal(this.href);
});
mainWindow.webContents.on('new-window', function(e, url) {
e.preventDefault();
require('electron').shell.openExternal(url);
});
Requires that you use target="_blank" on your anchor tags.
My code snippet clue accordingly to the depreciations in Electron version ^12.0.0
const win = new BrowserWindow();
win.webContents.setWindowOpenHandler(({ url }) => {
// config.fileProtocol is my custom file protocol
if (url.startsWith(config.fileProtocol)) {
return { action: 'allow' };
}
// open url in a browser and prevent default
shell.openExternal(url);
return { action: 'deny' };
});
To make all Electron links to open externally in the default OS browser you will have to add an onclick property to them and change the href property so it doesn't load anything in the Electron app.
You could use something like this:
aTags = document.getElementsByTagName("a");
for (var i = 0; i < aTags.length; i++) {
aTags[i].setAttribute("onclick","require('shell').openExternal('" + aTags[i].href + "')");
aTags[i].href = "#";
}
But make sure the entire document has loaded before doing this otherwise it is not going to work.
A more robust implementation would look like this:
if (document.readyState != "complete") {
document.addEventListener('DOMContentLoaded', function() {
prepareTags()
}, false);
} else {
prepareTags();
}
function prepareTags(){
aTags = document.getElementsByTagName("a");
for (var i = 0; i < aTags.length; i++) {
aTags[i].setAttribute("onclick","require('shell').openExternal('" + aTags[i].href + "')");
aTags[i].href = "#";
}
return false;
}
Remember that if you load external files you will have to make them go through this process as well after they are fully loaded.
Some handy solutions can be found in this gist.
By listening on the body, the following solutions will work on <a> tags that may not yet exist when the JavaScript runs, but only appear in the DOM at a later time.
This one by luizcarraro requires jQuery:
$('body').on('click', 'a', (event) => {
event.preventDefault();
require("electron").shell.openExternal(event.target.href);
});
You can change the selector to target only certain links, e.g. '#messages-view a' or 'a.open-external'.
Here is an alternative without any library (derived from zrbecker's):
document.body.addEventListener('click', event => {
if (event.target.tagName.toLowerCase() === 'a') {
event.preventDefault();
require("electron").shell.openExternal(event.target.href);
}
});
Consult the gist for more examples.
I use this method with Electron v.13.
We intercept the user's navigation (window.location) and open the URL in the default browser.
See the doc : https://www.electronjs.org/docs/latest/api/web-contents#event-will-navigate
const { shell } = require('electron');
window.webContents.on('will-navigate', function (e, url) {
e.preventDefault();
shell.openExternal(url);
});
On tsx syntax (Electron):
import { shell } from "electron";
shell.openExternal("http://www.google.com")
In the view component use simple a link:
<a href="https://google.com" target="_blank" rel="noreferrer">
<button type="button">
button title
</button>
</a>
And in file public/electron.js add default behavior for all a link navigations:
function createWindow() {
...
// Open urls in the user's browser
win.webContents.setWindowOpenHandler((edata) => {
shell.openExternal(edata.url);
return { action: "deny" };
});
}
To open an external link in an Electron's Project you will need the module Shell (https://www.electronjs.org/docs/api/shell#shell) and the method openExternal.
But if you are looking for an abstract way to implement that logic is by creating a handler for a custom target to your target attribute.
const {shell} = require('electron');
if (document.readyState != "complete") {
document.addEventListener('DOMContentLoaded', function() {
init()
}, false);
} else {
init();
}
function init(){
handleExternalLinks();
//other inits
}
function handleExternalLinks(){
let links = document.getElementsByTagName('a')
let a,i = 0;
while (links[i]){
a = links[i]
//If <a target="_external">, so open using shell.
if(a.getAttribute('target') == '_external'){
a.addEventListener('click',(ev => {
ev.preventDefault();
let url = a.href;
shell.openExternal(url);
a.setAttribute('href', '#');
return false;
}))
}
console.log(a,a.getAttribute('external'))
i++;
}
}
To run an Electron project in your actual browser (Chrome, Mozilla, etc), add this to your script are external script:
aTags = document.getElementsByTagName("a");
for (var i = 0; i < aTags.length; i++) {
aTags[i].setAttribute("onclick","require('shell').openExternal('" + aTags[i].href + "')");
aTags[i].href = "#";
}

Accessing file system using javascript in firefox or chrome?

I had been able to do this up until Firefox 15 using:
netscape.security.privilegeManager.enablePrivilege("UniversalXPConnect")
and setting the signed.applets.codebase_principal_support option to true. Unfortunately as of FF 17 this functionality has been removed. From what I understand Chrome has been the same way for some time now.
Does anyone know if there has been a Firefox or Chrome extension created that allows for the use of enablePrivilege? If not, recommendations on where to start if building my own?
File API, the reason those have stopped working is because both have now implemented the html5 file api.
Here is a html5 demo of the api.
Here is the relevant script in case they remove the demo:
<script>
var holder = document.getElementById('holder'),
state = document.getElementById('status');
if (typeof window.FileReader === 'undefined') {
state.className = 'fail';
} else {
state.className = 'success';
state.innerHTML = 'File API & FileReader available';
}
holder.ondragover = function () { this.className = 'hover'; return false; };
holder.ondragend = function () { this.className = ''; return false; };
holder.ondrop = function (e) {
this.className = '';
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function (event) {
console.log(event.target);
holder.style.background = 'url(' + event.target.result + ') no-repeat center';
};
console.log(file);
reader.readAsDataURL(file);
return false;
};
</script>
As a note: if you need to access a file on your local machine in chrome you need to run the program using this switch --allow-file-access-from-files (for using a file input without it actually loading to the server, otherwise you get a xhr cross-domain error).
I don't know of the equivalent in firefox.

Categories