UNPKG

@yookue/ts-lang-utils

Version:

Common lang utilities for typescript

40 lines 1.74 kB
var specialExtensions = ['doc', 'docx', 'docm', 'dot', 'dotx', 'dotm', 'xls', 'xlsx', 'xlsm', 'xlsb', 'xlam', 'xlt', 'xltx', 'xltm', 'ppt', 'pptx', 'pptm', 'pot', 'potx', 'potm', 'ppsx', 'ppsm', 'pps', 'wps', 'wpt', 'et', 'ett', 'dps', 'dpt', 'eio', 'eti', 'edp', 'uof', 'uot', 'uos', 'uop', 'smd', 'smt', 'smp', 'pdf', 'zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'exe', 'msi', 'dmg', 'iso']; export function downloadUrlByElement(url, fileName) { var _fileName$split$pop; if (!url) { return; } var sameOrigin = new URL(url, window.location.href).origin === window.location.origin; var fileExtension = fileName === null || fileName === void 0 || (_fileName$split$pop = fileName.split('.').pop()) === null || _fileName$split$pop === void 0 ? void 0 : _fileName$split$pop.toLowerCase(); var blobHandle = !sameOrigin || specialExtensions.includes(fileExtension !== null && fileExtension !== void 0 ? fileExtension : ''); if (!blobHandle) { var link = document.createElement('a'); if (fileName) { link.download = fileName; } link.href = url; document.body.appendChild(link); link.click(); document.body.removeChild(link); return; } window.fetch(url).then(function (response) { if (!response.ok) { throw new Error('Network response is not ok'); } return response.blob(); }).then(function (blob) { var blobUrl = window.URL.createObjectURL(blob); var link = document.createElement('a'); link.href = blobUrl; if (fileName) { link.download = fileName; } document.body.appendChild(link); link.click(); document.body.removeChild(link); window.URL.revokeObjectURL(blobUrl); }).catch(function () { window.open(url, '_blank'); }); }