如何将localStorage数据写入Chrome中的文本文件

How to write localStorage data to a text file in Chrome

本文关键字:Chrome 文本 文件 localStorage 数据      更新时间:2023-09-26

我想将localStorage项写入文本文件,并希望调用user将该文件存储在指定位置。请帮我扩展代码

  var data = JSON.parse(localStorage.getItem(pid));   
  var Text2Write = "";
  for(var pr in ele)
  {
     var dat = pr + ":" + ele[pr] + "'n";
     Text2Write += dat;
  }
  // Here I want to store this Text2Write to text file and ask user to save where he wants.  

请帮我扩展这个代码

我找到了这个控制台。Save (data, [filename])方法可以很容易地添加到控制台。注意,当文件被下载时,它会直接进入默认的下载文件夹。要添加它,只需运行:

(function(console){
    console.save = function(data, filename){
        if(!data) {
            console.error('Console.save: No data')
            return;
        }
        if(!filename) filename = 'console.json'
        if(typeof data === "object"){
            data = JSON.stringify(data, undefined, 4)
        }
        var blob = new Blob([data], {type: 'text/json'}),
            e    = document.createEvent('MouseEvents'),
            a    = document.createElement('a')
        a.download = filename
        a.href = window.URL.createObjectURL(blob)
        a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':')
        e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
        a.dispatchEvent(e)
    }
})(console)

然后像这样传入数据和文件名,console。保存(data, [filename]),文件将被创建并下载。

源:

https://plus.google.com/+ AddyOsmani/文章/jBS8CiNTESM

http://bgrins.github.io/devtools-snippets/console-save

如果您不想使用服务器端解决方案(当然不一定是PHP),最简单的方法是使用数据URI:

data:text/plain,Your text here

这将在浏览器中显示文本文件,并允许用户将其保存在他们想要的地方。我认为不可能为这些URI显示"另存为"对话框。

注意:这至少需要IE8。但我猜这是你的要求,因为你正在使用localStorage。

既然这个问题被标记为google-chrome-extension,我想为扩展开发者提供一个更简单的解决方案。

首先,在manifest.json

的权限中添加"downloads"
"permissions": [
    "downloads"
]

然后使用下载api和@emil-stenström提供的data:text/plain技巧。

var myString = localStorage.YOUR_VALUE;
chrome.downloads.download({
    url: "data:text/plain," + myString,
    filename: "data.txt",
    conflictAction: "uniquify", // or "overwrite" / "prompt"
    saveAs: false, // true gives save-as dialogue
}, function(downloadId) {
    console.log("Downloaded item with ID", downloadId);
});

为了适应JSON,只需用JSON.stringify(localStorage.YOUR_DATA)准备对象或数组,然后使用data:text/json并将文件结尾更改为.json

我还想将我的本地存储文本保存到一个文件中以供下载,并且代码可以在Mac上的Safari, Chrome和Firefox的桌面上工作。然而,我认为在iOS中不可能在Chrome或Firefox的任何地方保存Blob()。有趣的是,它在Safari中确实有效。例如,我可以将文本文件保存到我的Wunderlist应用程序。以下是我在Github上的repo链接:the Cat Whisperer on Github h-pages

下面是JavaScript代码:
const fileDownloadButton = document.getElementById('save');
function localStorageToFile() {
    const csv = JSON.stringify(localStorage['autosave']);
    const csvAsBlob = new Blob([csv], {type: 'text/plain'});
    const fileNameToSaveAs = 'local-storage.txt';
    const downloadLink = document.getElementById('save');
    downloadLink.download = fileNameToSaveAs;
    if (window.URL !== null) {
        // Chrome allows the link to be clicked without actually adding it to the DOM
        downloadLink.href = window.URL.createObjectURL(csvAsBlob);
        downloadLink.target = `_blank`;
    } else {
        downloadLink.href = window.URL.createObjectURL(csvAsBlob);
        downloadLink.target = `_blank`;
        downloadLink.style.display = 'none';
        // add .download so works in Firefox desktop.
        document.body.appendChild(downloadLink.download);
    }
    downloadLink.click();
}
// file download button event listener
fileDownloadButton.addEventListener('click', localStorageToFile);      

您必须将该内容写入可以用PHP下载的文本文件中。对于JavaScript,我认为这是不可能的。你可以发送post请求到一个php文件,它可以作为一个文本文件下载。