创建/下载扩展名为 chrome 的 .html 文件

Creating / downloading a .html file with a chrome extension

我正在构建我的第一个 Chrome 扩展。到目前为止,我的代码采用网页元素并创建 HTML 标记(加载到 Javascript 中的字符串)。

我的分机通过一个按钮引导

$(".column1").prepend('<div class="actions" style="margin-bottom: 1rem;"><button id="edmMaker">Make an EDM!</a></div>')
$('#edmMaker').click(function(){
    var html = "<body><section><h1>Here is some HTML text</h1></section><div><p>Here's some more</p></div></body>"
    // create a .html file and download it to the user's desktop
});

在 Node.JS 中,我只是将一个 .html 文件写入本地磁盘,但我不太明白这在 Chrome 扩展世界中是如何工作的。

我该怎么做?

子问题:有什么办法可以将正在输出的HTML制表吗?我输出的实际代码是一个 HTML 电子邮件模板,Javascript 只会让我加载一个没有换行符和制表符的字符串。

这是我写的一个利用 HTML5's download attribute 下载文件的方法:

var saveHTML = function(fileName, html){
    //  Escape HTML

    var el = document.createElement("dummy");
    el.innerText = html;

    var escapedHTML = el.innerHTML;

    //  Use dummy <a /> tag to save

    var link = document.createElement("a");
    link.download = fileName;
    link.href = "data:text/plain,"+escapedHTML;

    link.click(); // trigger click/download
};

saveHTML("myHTML.html", "<html></html>");

实际查看 here.

如果您不想保存文件,您可以使用 storage

编辑:

正如@Xan 在下面指出的那样,chrome.downloads API exists as well which may be of some use, specifically chrome.downloads.download() 方法。


对于tabs/spaces/newlines的多行字符串,有3种方式:

1.) 手动,使用换行符 (\n) 和制表符 (\t)

"<body>\n\t<section>\n\t\t<h1>Here is some HTML text</h1>\n\t</section>\n\t<div>\n\t\t<p>Here's some more</p>\n\t</div>\n</body>"

结果是:

<body>
    <section>
        <h1>Here is some HTML text</h1>
    </section>
    <div>
        <p>Here's some more</p>
    </div>
</body>

2.)使用JavaScript的多行字符串支持,需要在行尾插入反斜杠:

var html = "<body>\
    <section>\
        <h1>Here is some HTML text</h1>\
    </section>\
    <div>\
        <p>Here's some more</p>\
    </div>\
</body>";

3.) Array.join:

var html = [
    "<body>",
    "   <section>",
    "       <h1>Here is some HTML text</h1>",
    "   </section>",
    "   <div>",
    "       <p>Here's some more</p>",
    "   </div>",
    "</body>"
].join("\n");