data.text html,Convert HTML to data:text/html link using JavaScript

"本文详细介绍了数据URI(Uniform Resource Identifier)在HTML中的使用,特别是MIME类型为text/html时的格式要求。强调了非ASCII字符的处理,如添加charset=UTF-8,以及特殊字符的转义规则,包括#、%、"&"、"<"和">"。同时,提供了JavaScript实现数据URI的编码方法,考虑了大小和编码效率的问题。"
摘要由CSDN通过智能技术生成

Characteristics of a data-URI

A data-URI with MIME-type text/html has to be in one of these formats:

data:text/html,

data:text/html;charset=UTF-8,

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 in location.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:

var html = document.getElementById("html").innerHTML;

var dataURI = 'data:text/html,' + encodeURIComponent(html);

If size matters, you'd better strip out all consecutive white-space (this can safely be done, unless the HTML contains a

 element/style). Then, only replace the significant characters:

var html = document.getElementById("html").innerHTML;

html = html.replace(/\s{2,}/g, '') //

.replace(/%/g, '%25') //

.replace(/&/g, '%26') //

.replace(/#/g, '%23') //

.replace(/"/g, '%22') //

.replace(/'/g, '%27'); //

var dataURI = 'data:text/html;charset=UTF-8,' + html;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值