使用 Javascript 在本地保存 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27177661/
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
Save HTML locally with Javascript
提问by Basj
I do know that Javascript cannot write data in the filesystem, for security reasons. I have often read that the only way to save data locally with Javascript is cookies or localStorage.
我知道出于安全原因,Javascript 不能在文件系统中写入数据。我经常读到,使用 Javascript 在本地保存数据的唯一方法是 cookie 或localStorage.
But is it possible, in the very specific case when the file is accessed locally(and not through internet) to write data locally? (without any server language, and even without any server at all... just local browsing of a HTML file)
但是,在非常特殊的情况下,当在本地(而不是通过互联网)访问文件以在本地写入数据时,是否有可能?(没有任何服务器语言,甚至根本没有任何服务器......只是本地浏览 HTML 文件)
For example, would it be possible, by clicking on SAVEhere on this page...
例如,这将是可能的,通过点击SAVE这里这个页面上...
...that the HTML file is overwritten with its new content ? (i.e. the localHTML file should be updated when SAVEis pressed).
...HTML 文件被其新内容覆盖了吗?(即当按下SAVE时应该更新本地HTML 文件)。


Is this possible to SAVE a file thanks to Javascript, when the HTML page is accessed locally?
当在本地访问 HTML 页面时,这是否可以通过 Javascript 保存文件?
Note: I want to be able to silently save, not propose a Download/Save dialog box in which the user has to choose where to download, then "Are you sure to want to overwrite" etc.
注意:我希望能够静默保存,而不是提出一个下载/保存对话框,用户必须在其中选择下载位置,然后“您确定要覆盖吗”等。
EDIT: Why this question? I would like to be able to do a HTML/JS notepad that I can run locally without any server (no apache, no php). I need to be able to save easily without having to deal with Dialog Box "Where do you want to download the file?".
编辑:为什么这个问题?我希望能够做一个 HTML/JS 记事本,我可以在没有任何服务器的情况下在本地运行(没有 apache,没有 php)。我需要能够轻松保存而不必处理对话框“您想在哪里下载文件?”。
采纳答案by FlyingPiMonster
The canonical answer, from the W3C File API Standard:
来自W3C 文件 API 标准的规范答案:
User agents should provide an API exposed to script that exposes the features above. The user is notified by UI anytime interaction with the file system takes place, giving the user full ability to cancel or abort the transaction. The user is notified of any file selections, and can cancel these. No invocations to these APIs occur silently without user intervention.
用户代理应该提供一个暴露给脚本的 API,以暴露上述功能。用户在与文件系统交互的任何时候都会收到 UI 通知,让用户可以完全取消或中止事务。用户会收到任何文件选择的通知,并且可以取消这些选择。在没有用户干预的情况下,不会静默调用这些 API。
Basically, because of security settings, any time you download a file, the browser will make sure the user actually wants to save the file. Browsers don't really differentiate JavaScript on your computer and JavaScript from a web server. The only difference is how the browser accesses the file, so storing the page locally will not make a difference.
基本上,由于安全设置,每次下载文件时,浏览器都会确保用户确实想要保存文件。浏览器并没有真正区分计算机上的 JavaScript 和 Web 服务器上的 JavaScript。唯一的区别是浏览器访问文件的方式,因此将页面存储在本地不会有什么不同。
Workarounds:However, you could just store the innerHTML of the <div>in a cookie. When the user gets back, you can load it back from the cookie. Although it isn't exactly saving the file to the user's computer, it should have the same effect as overwriting the file. When the user gets back, they will see what they entered the last time. The disadvantage is that, if the user clears their website data, their information will be lost. Since ignoring a user's request to clear local storage is alsoa security problem, there really is no way around it.
解决方法:但是,您可以将 的innerHTML 存储<div>在cookie 中。当用户回来时,您可以从 cookie 中加载它。虽然它并没有完全将文件保存到用户的计算机上,但它应该具有与覆盖文件相同的效果。当用户返回时,他们将看到上次输入的内容。缺点是,如果用户清除他们的网站数据,他们的信息就会丢失。由于忽略用户清除本地存储的请求也是一个安全问题,因此确实没有办法绕过它。
However, you could also do the following:
但是,您也可以执行以下操作:
- Use a Java applet
- Use some other kind of applet
- Create a desktop (non-Web based) application
- Just remember to save the file when you clear your website data. You can create an alert that pops up and reminds you, or even opens the save window for you, when you exit the page.
- 使用 Java 小程序
- 使用其他类型的小程序
- 创建桌面(非基于 Web)应用程序
- 请记住在清除网站数据时保存文件。您可以创建一个警报,在您退出页面时弹出并提醒您,甚至为您打开保存窗口。
Using cookies:You canuse JavaScript cookies on a local page. Just put this in a file and open it in your browser:
使用 cookie:您可以在本地页面上使用 JavaScript cookie。只需将其放在一个文件中并在浏览器中打开它:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="timesVisited"></p>
<script type="text/javascript">
var timesVisited = parseInt(document.cookie.split("=")[1]);
if (isNaN(timesVisited)) timesVisited = 0;
timesVisited++;
document.cookie = "timesVisited=" + timesVisited;
document.getElementById("timesVisited").innerHTML = "You ran this snippet " + timesVisited + " times.";
</script>
</body>
</html>
回答by Awesomeness01
You can just use the Blob function:
你可以只使用 Blob 函数:
function save() {
var htmlContent = ["your-content-here"];
var bl = new Blob(htmlContent, {type: "text/html"});
var a = document.createElement("a");
a.href = URL.createObjectURL(bl);
a.download = "your-download-name-here.html";
a.hidden = true;
document.body.appendChild(a);
a.innerHTML = "something random - nobody will see this, it doesn't matter what you put here";
a.click();
}
and your file will save.
并且您的文件将保存。
回答by Teo Dragovic
Yes, it's possible.
是的,这是可能的。
In your example, you are already using ContentEditableand most of tutorials for that attribute have some sort of localStrorage example, ie. http://www.html5tuts.co.uk/demos/localstorage/
在您的示例中,您已经在使用ContentEditable并且该属性的大多数教程都有某种 localStorage 示例,即。http://www.html5tuts.co.uk/demos/localstorage/
On page load, script should check localStorage for data and if true, populate element. Any changes in content could be saved in localStorage when clicking save button (or automatically, in linked example, using blur and focus). Additionally you can use this snippet to check weather user is online or offline and based on state modify your logic:
在页面加载时,脚本应检查 localStorage 中的数据,如果为 true,则填充元素。单击保存按钮时,内容的任何更改都可以保存在 localStorage 中(或自动,在链接示例中,使用模糊和焦点)。此外,您可以使用此代码段来检查天气用户在线还是离线,并根据状态修改您的逻辑:
// check if online/offline
// http://www.kirupa.com/html5/check_if_internet_connection_exists_in_javascript.htm
function doesConnectionExist() {
var xhr = new XMLHttpRequest();
var file = "http://www.yoursite.com/somefile.png";
var randomNum = Math.round(Math.random() * 10000);
xhr.open('HEAD', file + "?rand=" + randomNum, false);
try {
xhr.send();
if (xhr.status >= 200 && xhr.status < 304) {
return true;
} else {
return false;
}
} catch (e) {
return false;
}
}
EDIT:More advance version of localStorage is Mozilla localForagewhich allows storing other types of data besides strings.
编辑:localStorage 的更高级版本是 Mozilla localForage,它允许存储除字符串之外的其他类型的数据。
回答by RadleyMith
You could save files, and make it persistent using the FileSystem-API and webkit. You would have to use a chrome browser and it is not a standards technology but I think it does exactly what you want it to do. Here is a great tutorial to show how to do just that http://www.noupe.com/design/html5-filesystem-api-create-files-store-locally-using-javascript-webkit.html
您可以保存文件,并使用 FileSystem-API 和 webkit 使其持久化。您将不得不使用 chrome 浏览器,它不是一种标准技术,但我认为它完全符合您的要求。这是一个很棒的教程,展示了如何做到这一点http://www.noupe.com/design/html5-filesystem-api-create-files-store-locally-using-javascript-webkit.html
And to show that its on topic it starts off showing you how to make the file save persistent...
为了表明它的主题,它开始向您展示如何使文件持久保存......
window.webkitRequestFileSystem(window.PERSISTENT , 1024*1024, SaveDatFileBro);
回答by Kirk Strobeck
Just use https://github.com/firebase/firepad— See it in action
This doesn't need a server on your computer, it will reach out and save the data remotely.
只需使用https://github.com/firebase/firepad—看到它在行动
这不需要您的计算机上的服务器,它会伸出手并远程保存数据。
回答by smcjones
I think it's important to clarify the difference between server and client in this context.
我认为在这种情况下澄清服务器和客户端之间的区别很重要。
Client/server is a program relationship in which one program (the client) requests a service or resource from another program (the server).
客户端/服务器是一种程序关系,其中一个程序(客户端)从另一个程序(服务器)请求服务或资源。
Source: http://searchnetworking.techtarget.com/definition/client-server
来源:http: //searchnetworking.techtarget.com/definition/client-server
I'm not sure you'll find too many advanced applications that don't have at least one server/client relationship. It is somewhat misleading to ask to achieve this without any server, because any time your program speaks to another program, it is a client/server relationship, with the requester being the client and the response coming from the server. This is even if you are working locally. When you want to do something outside of the scope of the browser, you need a hook in a server.
我不确定您会发现太多没有至少一种服务器/客户端关系的高级应用程序。要求在没有任何服务器的情况下实现这一点有点误导,因为任何时候你的程序与另一个程序对话,它都是客户端/服务器关系,请求者是客户端,响应来自服务器。即使您在本地工作也是如此。当你想做浏览器范围之外的事情时,你需要在服务器中使用钩子。
Now, that does not mean you can't achieve this without a server-side specific language. For example, this solutionuses NodeJS for the server. WinJS has WinJS.xhr, which uses XmlHttpRequestto serve data to the server.
现在,这并不意味着没有服务器端特定语言就无法实现这一点。例如,此解决方案使用 NodeJS 作为服务器。WinJS 有 WinJS.xhr,它使用XmlHttpRequest向服务器提供数据。
AJAX seeks to offer the same sort of functions. The point here is that whether you have a program or there is some sort of hook pre-built, when you issue a command like "save file" and the file actually gets saved, there is a program on the other side that is parsing it, whether it's a server-side language or something else, meaning you can't possibly have something like this function without a server to receive the request.
AJAX 寻求提供相同类型的功能。这里的重点是,无论您有程序还是预先构建了某种钩子,当您发出“保存文件”之类的命令并且文件实际被保存时,另一端有一个程序正在解析它,无论是服务器端语言还是其他语言,这意味着如果没有服务器接收请求,您就不可能拥有这样的功能。
回答by Tom-Oliver Heidel
Have a look into this :) Download File Using Javascript/jQuerythere should be everything you need. If you still need help or it's not the solution you need, tell me ;)
看看这个 :) 使用 Javascript/jQuery 下载文件应该有你需要的一切。如果您仍然需要帮助或者这不是您需要的解决方案,请告诉我;)
回答by Leo
Convert your HTML content to a data uri string, and set as hrefattribute of an anchor element. Don't forget to specify a filename as downloadattribute.
将您的 HTML 内容转换为数据 uri 字符串,并设置为href锚元素的属性。不要忘记指定文件名作为download属性。
Here's a simple example:
这是一个简单的例子:
<a>click to download</a>
<script>
var anchor = document.querySelector('a');
anchor.setAttribute('download', 'example.html');
anchor.setAttribute('href', 'data:text/html;charset=UTF-8,<p>asdf</p>');
</script>
Just try it in your browser, no server required.
只需在浏览器中尝试,无需服务器。
回答by Leftium
Yes, it ispossible. Proof by example:
是的,这是可能的。举例证明:
TiddlyFox:allows modification of local files via an add-on. (source code) (extension page):
TiddlyFox:允许通过附加组件修改本地文件。(源代码)(扩展页面):
TiddlyFox is an extension for Mozilla Firefox that enables TiddlyWiki to save changes directly to the file system.
TiddlyFox 是 Mozilla Firefox 的扩展,它使 TiddlyWiki 能够将更改直接保存到文件系统。
Todo.html:An HTML file that saves edits to itself. Currently, it only works in Internet Explorer and you have to confirm some security dialogs when first opening the file. (source code) (functional demo).
Todo.html:将编辑内容保存到自身的 HTML 文件。目前,它仅适用于 Internet Explorer,您必须在第一次打开文件时确认一些安全对话框。(源代码)(功能演示)。
Steps to confirm todo.html actually saves changes to itself locally:
确认 todo.html 的步骤实际上是在本地保存对自身的更改:
- Save todo.htmlto local harddrive
- Open with Internet Explorer. Accept all the security dialogs.
- Type command
todo add TEST(todo.html emulates the command-line interface of todo.txt-CLI) - Inspect todo.html file for addition of 'TEST'
- 将todo.html保存到本地硬盘
- 使用 Internet Explorer 打开。接受所有安全对话框。
- 输入命令
todo add TEST(todo.html 模拟todo.txt-CLI的命令行界面) - 检查 todo.html 文件以添加“测试”
Caveats:there is no cross-platform method. I'm not sure how much longer these methods will exist. When I first started my todo.html project, there was a jQuery plugin called twFilethat allowed cross-browser loading/saving of local files using four different methods (ActiveX, Mozilla XUL, Java applet, Java Live Connect). Except for ActiveX, browsers have disallowed all these methods due to security concerns.
警告:没有跨平台的方法。我不确定这些方法还会存在多久。当我第一次开始我的 todo.html 项目时,有一个名为twFile的 jQuery 插件,它允许使用四种不同的方法(ActiveX、Mozilla XUL、Java 小程序、Java Live Connect)跨浏览器加载/保存本地文件。除了 ActiveX,浏览器出于安全考虑不允许所有这些方法。
回答by Brayan Pastor
Use jsPDF -> https://github.com/MrRio/jsPDF
使用 jsPDF -> https://github.com/MrRio/jsPDF
<div id="content">
<h3>Hello, this is a H3 tag</h3>
<p>a pararaph</p>
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>
Javascript
Javascript
var doc = new jsPDF();
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
$('#cmd').click(function () {
doc.fromHTML($('#content').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.save('sample-file.pdf');
});

