我在一个站点上有一段代码,它将本地存储的内容导出到JSON格式的文件中。
因为某种原因它停止工作了。我在多个浏览器上测试过,但都一样.不会显示错误,但也不会导出错误。
不同的变量似乎很好,但它只是没有导出。
老实说,我不知道如何以不同的方式来做这件事,所以如果能提供任何帮助,我将不胜感激。
Thx
function exportHistory() {
console.log("started");
var _myArray = JSON.stringify(localStorage , null, 4); //indentation in json format, human readable
var vLink = document.getElementById('exportHistory'),
var vBlob = new Blob([_myArray], {type: "octet/stream"}),
vName = 'working_history_' + todayDate() + '.json',
vUrl = window.URL.createObjectURL(vBlob);
console.log(vLink);
vLink.setAttribute('href', vUrl);
vLink.setAttribute('download', vName );
console.log("finished");
}
<button class="btn btn-outline-secondary btn-sm" id="exportHistory" onclick="exportHistory()">Export History</button >发布于 2020-05-04 07:50:16
在这里,您需要将download属性添加到锚标记<a>,而不是单击按钮本身。您需要使用display:none创建一个锚标记,并以编程方式单击它来下载文件。下面是一个例子。注意,只用于执行函数的按钮,href和download属性被添加到<a>标记中。
function exportHistory() {
console.log("started");
var _myArray = JSON.stringify(localStorage , null, 4); //indentation in json format, human readable
//Note: We use the anchor tag here instead button.
var vLink = document.getElementById('exportHistoryLink');
var vBlob = new Blob([_myArray], {type: "octet/stream"});
vName = 'working_history_' + todayDate() + '.json';
vUrl = window.URL.createObjectURL(vBlob);
console.log(vLink);
vLink.setAttribute('href', vUrl);
vLink.setAttribute('download', vName );
//Note: Programmatically click the link to download the file
vLink.click();
console.log("finished");
}现在,向DOM添加一个空锚标记。
<button class="btn btn-outline-secondary btn-sm" id="exportHistory" onclick="exportHistory()">Export History</button >
<a id="exportHistoryLink" style="display: none;">Export</a>https://stackoverflow.com/questions/61586888
复制相似问题