2015-02-07 36 views
0

我正在构建我的第一个Chrome扩展。到目前为止,我的代码需要一个网页元素并创建HTML标记(在JavaScript中以字符串加载)。用铬扩展名创建/下载.html文件

我的扩展的按钮导致

$(".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只会让我加载一个没有换行符和制表符的字符串。

回答

1

这里是我写了一个方法,它利用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"); 
+1

\ *。咳咳\ * ['chrome.downloads'](https://developer.chrome.com/extensions/downloads)\ *咳嗽\ * – Xan 2015-02-07 15:35:43

+2

@Xan *编辑狂怒* – mattsven 2015-02-07 15:56:28

+1

@Xan其实,它看起来像'chrome.downloads。下载“的功能与我上面的功能非常相似。无论如何我都会收录它。我也不能告诉它它会接受一个数据URI(可能) – mattsven 2015-02-07 15:59:27

相关问题