将mavascript blob变量下载为mhtml

时间:2012-02-11 22:39:03

标签: javascript google-chrome-extension

我正在编写一个使用

的Google Chrome扩展程序
chrome.pageCapture.saveAsMHTML(object details, function callback)
function callback (blob mhtmlData) {...};

http://code.google.com/chrome/extensions/dev/pageCapture.html

基本上将mhtml页面的blob表示存储到变量中。

现在我想让用户将此blob变量下载为mhtml文件..

我尝试了这个,但它给了我一个200kb的文件,里面填充了随机字符。

chrome.pageCapture.saveAsMHTML({tabId: sender.tab.id}, function callback(mhtml){

    var reader = new FileReader();
    reader.readAsDataURL(mhtml);

    reader.onload = function(e) {
        window.open(e.target.result);
    }


}); 

2 个答案:

答案 0 :(得分:4)

以下是我在页面操作弹出窗口中放入的一些代码。我留下了我没用过的东西,但将其评论出来作为参考 修改
使用https://github.com/eligrey/FileSaver.js中的库很容易,也许你可以看一下,看看他们在做什么。

<强> popup.html

<html>
<head>
<script xmlns="http://www.w3.org/1999/xhtml" type="application/ecmascript" async="" src="https://raw.github.com/eligrey/FileSaver.js/master/FileSaver.min.js"></script>
<script>
function onLoad(){
var downloadLink = document.querySelector("#MHTML");

var oFReader = new FileReader();
oFReader.onload = function (oFREvent) {
// None of the following worked
  //window.open('data:application/octet-stream;'+oFREvent.target.result.slice(5));
  //window.open('data:application/message/rfc822;'+oFREvent.target.result.slice(5));
  //window.open(oFREvent.target.result);
};

chrome.tabs.getSelected(null, function(tab) {

chrome.pageCapture.saveAsMHTML({tabId: tab.id}, function (mhtml){

/// Works but requires user input
//downloadLink.setAttribute('download',tab.title+'.mhtml');
//downloadLink.setAttribute('href',window.webkitURL.createObjectURL(mhtml));

///Works but awful filename without extension
//window.open(window.webkitURL.createObjectURL(mhtml));

///Doesnt work
//oFReader.readAsDataURL(mhtml);

///Using https://github.com/eligrey/FileSaver.js , works great
saveAs(mhtml, tab.title+'.mhtml');
})
});

}
</script>
</head>
<body onload="onLoad();" style="width: 400px">

<a id="MHTML" href="#">Download Page As MHTML</a>

</body>
</html>

答案 1 :(得分:0)

如果要为文件命名,可以使用锚元素并以编程方式设置下载属性的名称:

var reader = new FileReader();
reader.readAsDataURL(mhtml);

reader.onloadend = function(e) {
  const dataUrl = e.target.result;
  const a = document.createElement('a');
  a.href = dataUrl;
  a.download = fileName;
  a.click();
}