我正在构建我的第一个 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 也存在,可能会有一些用处,特别是 chrome.downloads.download()
方法。
对于带有制表符/空格/换行符的多行字符串,有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");
关于javascript - 创建/下载带有 chrome 扩展名的 .html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28378708/