创建/下载一个带有chrome扩展名的.html文件

Creating / downloading a .html file with a chrome extension

本文关键字:chrome 扩展名 文件 html 一个 下载 创建      更新时间:2023-09-26

我正在构建我的第一个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的下载属性来下载文件:

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>");

点击此处查看它的实际操作

如果您不想保存文件,可以使用存储空间。

编辑:

正如@Xan在下面指出的,chrome.downloads API也存在,它可能有一些用途,特别是chrome.downloads.download()方法。


对于带有制表符/空格/换行符的多行字符串,有三种方法:

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");