Created
March 16, 2016 15:18
-
-
Save jaxxreal/2db6127c473bb7a97621 to your computer and use it in GitHub Desktop.
Crossbrowser file download
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var BrowserDetect = | |
{ | |
init: function () { | |
this.browser = this.searchString(this.dataBrowser) || 'Other'; | |
this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || 'Unknown'; | |
}, | |
searchString: function (data) { | |
for (var i = 0; i < data.length; i++) { | |
var dataString = data[i].string; | |
this.versionSearchString = data[i].subString; | |
if (dataString.indexOf(data[i].subString) != -1) { | |
return data[i].identity; | |
} | |
} | |
}, | |
searchVersion: function (dataString) { | |
var index = dataString.indexOf(this.versionSearchString); | |
if (index == -1) return; | |
return parseFloat(dataString.substring(index + this.versionSearchString.length + 1)); | |
}, | |
dataBrowser: [ | |
{string: navigator.userAgent, subString: 'Chrome', identity: 'Chrome'}, | |
{string: navigator.userAgent, subString: 'MSIE', identity: 'Explorer'}, | |
{string: navigator.userAgent, subString: 'Firefox', identity: 'Firefox'}, | |
{string: navigator.userAgent, subString: 'Safari', identity: 'Safari'}, | |
{string: navigator.userAgent, subString: 'Opera', identity: 'Opera'} | |
] | |
}; | |
if (global) BrowserDetect.init(); | |
export function downloadFile(sUrl) { | |
//iOS devices do not support downloading. We have to inform user about this. | |
if (/(iP)/g.test(navigator.userAgent)) { | |
alert('Your device does not support files downloading. Please try again in desktop browser.'); | |
return false; | |
} | |
//If in Chrome or Safari - download via virtual link click | |
if (BrowserDetect.browser == 'Chrome' || BrowserDetect.browser == 'Safari') { | |
//Creating new link node. | |
var link = document.createElement('a'); | |
link.href = sUrl; | |
if (link.download !== undefined) { | |
//Set HTML5 download attribute. This will prevent file from opening if supported. | |
var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length); | |
link.download = fileName; | |
} | |
//Dispatching click event. | |
if (document.createEvent) { | |
var e = document.createEvent('MouseEvents'); | |
e.initEvent('click', true, true); | |
link.dispatchEvent(e); | |
return true; | |
} | |
} | |
// Force file download (whether supported by server). | |
var query = '?download'; | |
global.open(sUrl + query, '_self'); | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment