javascript 如何将 localStorage 数据写入 Chrome 中的文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8693289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write localStorage data to a text file in Chrome
提问by Santiago Angel
I want to write a localStorage item to a text file and want to invoke user to store the file in a specified location. Please help me with extending the code
我想将 localStorage 项写入文本文件,并希望调用用户将文件存储在指定位置。请帮我扩展代码
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.
Please help me extending this code.
请帮助我扩展此代码。
采纳答案by Emil Stenstr?m
If you don't want to use a server-side solution (does not have to be PHP of course), the easiest way is to use a data URI:
如果您不想使用服务器端解决方案(当然不必是 PHP),最简单的方法是使用数据 URI:
data:text/plain,Your text here
This will show the text file in the browser, and let the user save it where they want. I don't think it's possible to show a "Save as"-dialog for those kind of URI:s.
这将在浏览器中显示文本文件,并让用户将其保存在他们想要的位置。我认为不可能为那种 URI:s 显示“另存为”对话框。
Note: this requires IE8 at least. But I'm guessing that's your requirement anyway, since you are using localStorage.
注意:这至少需要 IE8。但我猜这无论如何都是您的要求,因为您使用的是 localStorage。
回答by Santiago Angel
I found this console.save(data, [filename]) method you can add to the console that does the trick pretty easily. Note that when the file is downloaded it just goes directly into the default downloads folder. To add it simply run:
我发现了这个 console.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)
Then pass in the data and filename like so, console.save(data, [filename]) and the file will be created and downloaded.
然后像这样传入数据和文件名,console.save(data, [filename]) 并且文件将被创建和下载。
Source:
来源:
https://plus.google.com/+AddyOsmani/posts/jBS8CiNTESM
https://plus.google.com/+AddyOsmani/posts/jBS8CiNTESM
回答by Michael Johansen
Since the question is tagged with google-chrome-extension I want to provide a simpler solution for extension developers.
由于问题带有 google-chrome-extension 标记,我想为扩展程序开发人员提供一个更简单的解决方案。
First, add "downloads" to permissions in manifest.json
首先,在权限中添加“下载” manifest.json
"permissions": [
"downloads"
]
Then use the downloads-API with the data:text/plain
trick as provided by @emil-stenstr?m.
然后使用data:text/plain
@emil-stenstr?m 提供的技巧和下载 API 。
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);
});
To adapt for JSON, just prepare your object or array with JSON.stringify(localStorage.YOUR_DATA)
, then use data:text/json
and change the file ending to .json
要适应 JSON,只需使用 准备对象或数组JSON.stringify(localStorage.YOUR_DATA)
,然后使用data:text/json
并将文件结尾更改为.json
回答by Maria Campbell
I also had wanted to save my local storage text to a file for download and the code works on desktop for Safari, Chrome and Firefox on Mac. However, I think it is impossible in iOS to save the Blob() anywhere with Chrome or Firefox. It does work, interestingly enough in Safari. For example, I can save the text file to my Wunderlist app. Here is the link my repo on Github: The Cat Whisperer on Github gh-pages
我还想将我的本地存储文本保存到一个文件中以供下载,并且该代码适用于 Mac 上的 Safari、Chrome 和 Firefox 桌面。但是,我认为在 iOS 中不可能使用 Chrome 或 Firefox 将 Blob() 保存在任何地方。它确实有效,有趣的是在 Safari 中。例如,我可以将文本文件保存到我的奇妙清单应用中。这是我在 Github 上的回购链接:Github gh-pages 上的猫语者
Here is the JavaScript code:
这是 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);
回答by Dion
You have to write that content into a textfile which can be downloaded with PHP. With JavaScript this isn't possible I think. You could send an POST-request to a php file which can be downloaded as a text file.
您必须将该内容写入可以使用 PHP 下载的文本文件中。使用 JavaScript,我认为这是不可能的。您可以将 POST 请求发送到可以作为文本文件下载的 php 文件。