vanillajs-browser-helpers
Version:
Collection of convenience code snippets (helpers) that aims to make it a little easier to work with vanilla JS in the browser
40 lines (39 loc) • 1.32 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fileSavingSupported = void 0;
const isBlob_1 = __importDefault(require("./isBlob"));
const MSSave = 'msSaveBlob' in navigator;
function fileSavingSupported() {
return 'Blob' in window && (MSSave || 'download' in HTMLAnchorElement.prototype);
}
exports.fileSavingSupported = fileSavingSupported;
/**
* Creates a file with given content and triggers download.
* (if the browser doesn't support file downloads, this method does nothing)
*
* @param content - The content of the file
* @param name - The name to give the downloaded file
* @param type - The content type of the file
*/
function saveFile(content, name, type = 'text/plain; charset=utf-8') {
if (!fileSavingSupported()) {
return;
}
if (!isBlob_1.default(content)) {
content = new Blob([`${content}`], { type });
}
if (MSSave) {
navigator.msSaveBlob(content);
}
else {
const a = document.createElement('a');
a.download = name;
a.target = '_blank';
a.href = URL.createObjectURL(content);
a.click();
}
}
exports.default = saveFile;