Javascript导出本地存储

标签 javascript json download export local-storage

我在一个网站上有这段代码,它将本地存储的内容导出到 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 标记。并以编程方式单击它来下载文件。这是一个例子。请注意,该按钮仅用于执行该功能,并且 hrefdownload属性被添加到 <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/

相关文章:

javascript - 我的气球停止移动

javascript - setTimeout 返回 Uncaught TypeError : Illegal invocation in AudioContext in Chrome 错误

java - 使用 JSON 和 Hibernate JPA 进行无限递归

java - 流媒体上传/下载

java - 是否可以从 JSP 下载二进制文件?

javascript - 如何将位图嵌入到 D3js 生成的 SVG 代码中?

Javascript - 如何从 Accordion 中获取值到表单中

c# - Live HighChart 不显示数据

javascript - 如何将 google LatLng 对象字符串化?

iphone - 如何在iOS中下载队列中的多个文件