使用 JavaScript 将 HTML 转换为 data:text/html 链接
这是我的 HTML:
<a>View it in your browser</a>
<div id="html">
<h1>Doggies</h1>
<p style="color:blue;">Kitties</p>
</div>
如何使用 JavaScript 使链接的 href
属性指向一个 base64 编码的网页,其源是 div#html< 的
innerHTML
/代码>?
我基本上想在此处进行相同的转换(选中base64复选框) JavaScript 中除外。
Here's my HTML:
<a>View it in your browser</a>
<div id="html">
<h1>Doggies</h1>
<p style="color:blue;">Kitties</p>
</div>
How do I use JavaScript to make the href
attribute of my link point to a base64 encoded webpage whose source is the innerHTML
of div#html
?
I basically want to do the same conversion done here (with the base64 checkbox checked) except for in JavaScript.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
data-URI A data-URI 的特征
MIME 类型
text/html< 的 /code> 必须采用以下格式之一:
Base-64 编码不是必需的。如果您的代码包含非 ASCII 字符,例如
éé
,则必须添加charset=UTF-8
。以下字符必须转义:
#
- Firefox 和 Opera 将此字符解释为哈希标记(如location.hash
中所示)。%
- 该字符用于转义字符。转义该字符以确保不会发生副作用。此外,如果要将代码嵌入到锚标记中,还应转义以下字符:
" 和/或 '
- 引号标记属性的值。& - & 符号用于标记
<
和>
不必在 HTML 中转义。属性但是,如果您要将链接嵌入到 HTML 中,这些也应该被转义(%3C 和 %3E
)JavaScript 实现
如果您不介意 data-URI 的大小,这是最简单的方法为此,请使用
encodeURIComponent
:如果尺寸重要的是,你最好去掉所有连续的空格(这可以安全地完成,除非 HTML 包含
Characteristics of a data-URI
A data-URI with MIME-type
text/html
has to be in one of these formats:Base-64 encoding is not necessary. If your code contains non-ASCII characters, such as
éé
,charset=UTF-8
has to be added.The following characters have to be escaped:
#
- Firefox and Opera interpret this character as the marker of a hash (as inlocation.hash
).%
- This character is used to escape characters. Escape this character to make sure that no side effects occur.Additionally, if you want to embed the code in an anchor tag, the following characters should also be escaped:
" and/or '
- Quotes mark the value of the attribute.&
- The ampersand is used to mark HTML entities.<
and>
do not have to be escaped inside a HTML attribute. However, if you're going to embed the link in the HTML, these should also be escaped (%3C and %3E
)JavaScript implementation
If you don't mind the size of the data-URI, the easiest method to do so is using
encodeURIComponent
:If size matters, you'd better strip out all consecutive white-space (this can safely be done, unless the HTML contains a
<pre>
element/style). Then, only replace the significant characters:如果大小很重要,您最好去掉所有连续的空白(这可以安全地完成,除非 HTML 包含
If size matters, you'd better strip out all consecutive white-space (this can safely be done, unless the HTML contains a
<pre>
element/style). Then, only replace the significant characters: