我在一个网站上有这段代码,它将本地存储的内容导出到 JSON 格式的文件。
由于某种原因它停止工作了。我在多个浏览器中测试了它,但都是一样的......
没有显示错误,但也不导出。
不同的变量看起来不错,但它只是没有导出。
老实说,我不知道如何以不同的方式做到这一点,因此我们将不胜感激。
谢谢
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 >
最佳答案
这里需要添加download
anchor 标记的属性 <a>
而不是点击按钮本身。您需要使用display:none
创建一个 anchor 标记。并以编程方式单击它来下载文件。这是一个例子。请注意,该按钮仅用于执行该功能,并且 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 添加一个空 anchor 标记。
<button class="btn btn-outline-secondary btn-sm" id="exportHistory" onclick="exportHistory()">Export History</button >
<a id="exportHistoryLink" style="display: none;">Export</a>
关于Javascript导出本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61586888/