javascript 如何在本地保存网页,包括图片等
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11271898/
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 save a webpage locally including pictures,etc
提问by prabhakaran
I am building an add-on for an application. The clients are paying to view some webpages and download some files out of it. They want to automate this downloading process by add-on. So instead of selecting "Save Page as" and waiting for the download's completion, they can click the add-on and forget the process. The problem is, the webpage is providing some cookies to the browser. So the best way is File-> "Save Page As" . I want to do it through the add-on. Is there any firefox-javascript way for this?. I used nsiDownloader. But it saves only html, not the pictures,etc. Can anybody guide me in this issue?
我正在为应用程序构建附加组件。客户付费查看一些网页并从中下载一些文件。他们希望通过附加组件自动执行此下载过程。因此,与其选择“页面另存为”并等待下载完成,他们可以单击加载项并忘记该过程。问题是,该网页正在向浏览器提供一些 cookie。所以最好的方法是 File-> "Save Page As" 。我想通过附加组件来做到这一点。是否有任何 firefox-javascript 方式?我使用了 nsiDownloader。但它只保存 html,不保存图片等。有人可以在这个问题上指导我吗?
EDIT:Hi, This is the code which did the trick, thanks to sai prasad
编辑:嗨,这是成功的代码,感谢 sai prasad
var dir =Components.classes["@mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsILocalFile);
dir.initWithPath("C:\filename");
var file = Components.classes["@mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("C:\filename.html");
var wbp = Components.classes['@mozilla.org/embedding/browser/nsWebBrowserPersist;1']
.createInstance(Components.interfaces.nsIWebBrowserPersist);
alert("going to save");
wbp.saveDocument(content.document, file,dir, null, null, null);
alert("saved");
EDIT:But, still some webpages are not saved exactly as "Save Page as". Those saved pages are not rendered like original pages, they are look like some html example.
编辑:但是,仍然有些网页没有完全保存为“将页面另存为”。那些保存的页面不像原始页面那样呈现,它们看起来像一些 html 示例。
采纳答案by Sai Prasad
Since you mention that File->"Save Page As" is working as expected, I tried looking through the source code (chrome://browser/content/browser.xul) and found this:
由于您提到文件->“另存页面为”按预期工作,我尝试查看源代码(chrome://browser/content/browser.xul)并发现:
https://developer.mozilla.org/en/nsIWebBrowserPersist#saveDocument()
https://developer.mozilla.org/en/nsIWebBrowserPersist#saveDocument()
Make sure that you shall call this function only after the webpage is completely loaded (not DOMContentLoaded)!!
确保只有在网页完全加载(而不是 DOMContentLoaded)后才调用此函数!!