And*_*y E 42 html javascript internet-explorer dom
这是我一直遇到的一些困难.我有一个本地客户端脚本,需要允许用户获取远程网页并搜索结果页面的表单.为了做到这一点(没有正则表达式),我需要将文档解析为完全可遍历的DOM对象.
我想强调的一些限制:
getElementsByTagName需要提供DOM API等.假设我在变量中有一个完整的HTML文档字符串(包括DOCTYPE声明)html,这是我到目前为止所尝试的:
var frag = document.createDocumentFragment(),
div = frag.appendChild(document.createElement("div"));
div.outerHTML = html;
//-> results in an empty fragment
div.insertAdjacentHTML("afterEnd", html);
//-> HTML is not added to the fragment
div.innerHTML = html;
//-> Error (expected, but I tried it anyway)
var doc = new ActiveXObject("htmlfile");
doc.write(html);
doc.close();
//-> JavaScript executes
Run Code Online (Sandbox Code Playgroud)
我也尝试从HTML中提取<head>和<body>节点,并将它们添加到<HTML>片段内的元素,仍然没有运气.
有没有人有任何想法?
Rob*_*b W 79
小提琴:http://jsfiddle.net/JFSKe/6/
DocumentFragment没有实现DOM方法.使用document.createElement结合 innerHTML移除<head>和<body>标签(即使当创建的元素是一个根元素,<html>).因此,应该在其他地方寻求解决方案.我创建了一个跨浏览器的字符串到DOM函数,它使用了一个不可见的内联框架.
将禁用所有外部资源和脚本.有关更多信息,请参阅代码说明.
/*
@param String html The string with HTML which has be converted to a DOM object
@param func callback (optional) Callback(HTMLDocument doc, function destroy)
@returns undefined if callback exists, else: Object
HTMLDocument doc DOM fetched from Parameter:html
function destroy Removes HTMLDocument doc. */
function string2dom(html, callback){
/* Sanitise the string */
html = sanitiseHTML(html); /*Defined at the bottom of the answer*/
/* Create an IFrame */
var iframe = document.createElement("iframe");
iframe.style.display = "none";
document.body.appendChild(iframe);
var doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc.write(html);
doc.close();
function destroy(){
iframe.parentNode.removeChild(iframe);
}
if(callback) callback(doc, destroy);
else return {"doc": doc, "destroy": destroy};
}
/* @name sanitiseHTML
@param String html A string representing HTML code
@return String A new string, fully stripped of external resources.
All "external" attributes (href, src) are prefixed by data- */
function sanitiseHTML(html){
/* Adds a <!-\"'--> before every matched tag, so that unterminated quotes
aren't preventing the browser from splitting a tag. Test case:
'<input style="foo;b:url(0);><input onclick="<input type=button onclick="too() href=;>">' */
var prefix = "<!--\"'-->";
/*Attributes should not be prefixed by these characters. This list is not
complete, but will be sufficient for this function.
(see http://www.w3.org/TR/REC-xml/#NT-NameChar) */
var att = "[^-a-z0-9:._]";
var tag = "<[a-z]";
var any = "(?:[^<>\"']*(?:\"[^\"]*\"|'[^']*'))*?[^<>]*";
var etag = "(?:>|(?=<))";
/*
@name ae
@description Converts a given string in a sequence of the
original input and the HTML entity
@param String string String to convert
*/
var entityEnd = "(?:;|(?!\\d))";
var ents = {" ":"(?:\\s| ?|�*32"+entityEnd+"|�*20"+entityEnd+")",
"(":"(?:\\(|�*40"+entityEnd+"|�*28"+entityEnd+")",
")":"(?:\\)|�*41"+entityEnd+"|�*29"+entityEnd+")",
".":"(?:\\.|�*46"+entityEnd+"|�*2e"+entityEnd+")"};
/*Placeholder to avoid tricky filter-circumventing methods*/
var charMap = {};
var s = ents[" "]+"*"; /* Short-hand space */
/* Important: Must be pre- and postfixed by < and >. RE matches a whole tag! */
function ae(string){
var all_chars_lowercase = string.toLowerCase();
if(ents[string]) return ents[string];
var all_chars_uppercase = string.toUpperCase();
var RE_res = "";
for(var i=0; i<string.length; i++){
var char_lowercase = all_chars_lowercase.charAt(i);
if(charMap[char_lowercase]){
RE_res += charMap[char_lowercase];
continue;
}
var char_uppercase = all_chars_uppercase.charAt(i);
var RE_sub = [char_lowercase];
RE_sub.push("�*" + char_lowercase.charCodeAt(0) + entityEnd);
RE_sub.push("�*" + char_lowercase.charCodeAt(0).toString(16) + entityEnd);
if(char_lowercase != char_uppercase){
RE_sub.push("�*" + char_uppercase.charCodeAt(0) + entityEnd);
RE_sub.push("�*" + char_uppercase.charCodeAt(0).toString(16) + entityEnd);
}
RE_sub = "(?:" + RE_sub.join("|") + ")";
RE_res += (charMap[char_lowercase] = RE_sub);
}
return(ents[string] = RE_res);
}
/*
@name by
@description second argument for the replace function.
*/
function by(match, group1, group2){
/* Adds a data-prefix before every external pointer */
return group1 + "data-" + group2
}
/*
@name cr
@description Selects a HTML element and performs a
search-and-replace on attributes
@param String selector HTML substring to match
@param String attribute RegExp-escaped; HTML element attribute to match
@param String marker Optional RegExp-escaped; marks the prefix
@param String delimiter Optional RegExp escaped; non-quote delimiters
@param String end Optional RegExp-escaped; forces the match to
end before an occurence of <end> when
quotes are missing
*/
function cr(selector, attribute, marker, delimiter, end){
if(typeof selector == "string") selector = new RegExp(selector, "gi");
marker = typeof marker == "string" ? marker : "\\s*=";
delimiter = typeof delimiter == "string" ? delimiter : "";
end = typeof end == "string" ? end : "";
var is_end = end && "?";
var re1 = new RegExp("("+att+")("+attribute+marker+"(?:\\s*\"[^\""+delimiter+"]*\"|\\s*'[^'"+delimiter+"]*'|[^\\s"+delimiter+"]+"+is_end+")"+end+")", "gi");
html = html.replace(selector, function(match){
return prefix + match.replace(re1, by);
});
}
/*
@name cri
@description Selects an attribute of a HTML element, and
performs a search-and-replace on certain values
@param String selector HTML element to match
@param String attribute RegExp-escaped; HTML element attribute to match
@param String front RegExp-escaped; attribute value, prefix to match
@param String flags Optional RegExp flags, default "gi"
@param String delimiter Optional RegExp-escaped; non-quote delimiters
@param String end Optional RegExp-escaped; forces the match to
end before an occurence of <end> when
quotes are missing
*/
function cri(selector, attribute, front, flags, delimiter, end){
if(typeof selector == "string") selector = new RegExp(selector, "gi");
flags = typeof flags == "string" ? flags : "gi";
var re1 = new RegExp("("+att+attribute+"\\s*=)((?:\\s*\"[^\"]*\"|\\s*'[^']*'|[^\\s>]+))", "gi");
end = typeof end == "string" ? end + ")" : ")";
var at1 = new RegExp('(")('+front+'[^"]+")', flags);
var at2 = new RegExp("(')("+front+"[^']+')", flags);
var at3 = new RegExp("()("+front+'(?:"[^"]+"|\'[^\']+\'|(?:(?!'+delimiter+').)+)'+end, flags);
var handleAttr = function(match, g1, g2){
if(g2.charAt(0) == '"') return g1+g2.replace(at1, by);
if(g2.charAt(0) == "'") return g1+g2.replace(at2, by);
return g1+g2.replace(at3, by);
};
html = html.replace(selector, function(match){
return prefix + match.replace(re1, handleAttr);
});
}
/* <meta http-equiv=refresh content=" ; url= " > */
html = html.replace(new RegExp("<meta"+any+att+"http-equiv\\s*=\\s*(?:\""+ae("refresh")+"\""+any+etag+"|'"+ae("refresh")+"'"+any+etag+"|"+ae("refresh")+"(?:"+ae(" ")+any+etag+"|"+etag+"))", "gi"), "<!-- meta http-equiv=refresh stripped-->");
/* Stripping all scripts */
html = html.replace(new RegExp("<script"+any+">\\s*//\\s*<\\[CDATA\\[[\\S\\s]*?]]>\\s*</script[^>]*>", "gi"), "<!--CDATA script-->");
html = html.replace(/<script[\S\s]+?<\/script\s*>/gi, "<!--Non-CDATA script-->");
cr(tag+any+att+"on[-a-z0-9:_.]+="+any+etag, "on[-a-z0-9:_.]+"); /* Event listeners */
cr(tag+any+att+"href\\s*="+any+etag, "href"); /* Linked elements */
cr(tag+any+att+"src\\s*="+any+etag, "src"); /* Embedded elements */
cr("<object"+any+att+"data\\s*="+any+etag, "data"); /* <object data= > */
cr("<applet"+any+att+"codebase\\s*="+any+etag, "codebase"); /* <applet codebase= > */
/* <param name=movie value= >*/
cr("<param"+any+att+"name\\s*=\\s*(?:\""+ae("movie")+"\""+any+etag+"|'"+ae("movie")+"'"+any+etag+"|"+ae("movie")+"(?:"+ae(" ")+any+etag+"|"+etag+"))", "value");
/* <style> and < style= > url()*/
cr(/<style[^>]*>(?:[^"']*(?:"[^"]*"|'[^']*'))*?[^'"]*(?:<\/style|$)/gi, "url", "\\s*\\(\\s*", "", "\\s*\\)");
cri(tag+any+att+"style\\s*="+any+etag, "style", ae("url")+s+ae("(")+s, 0, s+ae(")"), ae(")"));
/* IE7- CSS expression() */
cr(/<style[^>]*>(?:[^"']*(?:"[^"]*"|'[^']*'))*?[^'"]*(?:<\/style|$)/gi, "expression", "\\s*\\(\\s*", "", "\\s*\\)");
cri(tag+any+att+"style\\s*="+any+etag, "style", ae("expression")+s+ae("(")+s, 0, s+ae(")"), ae(")"));
return html.replace(new RegExp("(?:"+prefix+")+", "g"), prefix);
}
Run Code Online (Sandbox Code Playgroud)
该sanitiseHTML功能基于我的replace_all_rel_by_abs功能(请参阅此答案).sanitiseHTML尽管如此,该功能已完全重写,以实现最高效率和可靠性.
此外,还添加了一组新的RegExps以删除所有脚本和事件处理程序(包括CSS expression(),IE7-).为确保按预期解析所有标记,调整后的标记将作为前缀<!--'"-->.此前缀对于正确解析嵌套的"事件处理程序"以及未终止的引号是必需的:<a id="><input onclick="<div onmousemove=evil()>">.
这些正则表达式是使用内部函数动态创建cr/ cri(ç reate ř E放置[ 我 n线段]).这些函数接受参数列表,并创建和执行高级RE替换.为了确保HTML实体没有违反一个RegExp(refresh在<meta http-equiv=refresh>可以写成各种方式),动态创建的正则表达式的一部分被构造函数ae(一个纽约ê ntity).
实际的更换是由函数来完成by(替换用).在此实现中,在所有匹配的属性之前by添加data-.
<script>//<[CDATA[ .. //]]></script>出现都是条纹的.此步骤是必需的,因为CDATA部分允许 </script>代码中的字符串.更换完成后,可以安全地进行下一次更换:<script>...</script>标签将被删除.<meta http-equiv=refresh .. >标记将被删除所有的事件侦听器和外部指针/属性(href,src,url())由前缀data-,如先前所描述.
IFrame创建一个对象.IFrame不太可能泄漏内存(与htmlfile ActiveXObject相反).IFrame变为不可见,并附加到文档中,以便可以访问DOM.document.write()用于将HTML写入IFrame.document.open()并document.close()用于清空文档的先前内容,以便生成的文档是给定html字符串的精确副本.
document对象的引用.该第二参数是一个函数被调用时它破坏所生成的DOM树.当您不再需要树时,应该调用此函数.doc和destroy),其具有相同的行为如前面提到的参数.designMode属性设置为"开"将停止执行脚本(Chrome不支持).如果<script>由于特定原因必须保留标记,则可以使用iframe.designMode = "On"而不是脚本剥离功能.htmlfile activeXObject.根据这个来源,htmlfile比IFrame慢,并且更容易受到内存泄漏的影响.href,, src...)都以前缀为前缀data-.获得/改变这些属性中的一个例子示出了用于data-href:elem.getAttribute("data-href")和elem.setAttribute("data-href", "...")elem.dataset.href和elem.dataset.href = "...".<link rel="stylesheet" href="main.css" /><script>document.body.bgColor="red";</script><img src="128x128.png" /> sanitiseHTML(html)
将此书签粘贴到位置栏中.它将提供一个注入textarea的选项,显示已清理的HTML字符串.
javascript:void(function(){var s=document.createElement("script");s.src="http://rob.lekensteyn.nl/html-sanitizer.js";document.body.appendChild(s)})();
Run Code Online (Sandbox Code Playgroud)
代码示例 -string2dom(html):
string2dom("<html><head><title>Test</title></head></html>", function(doc, destroy){
alert(doc.title); /* Alert: "Test" */
destroy();
});
var test = string2dom("<div id='secret'></div>");
alert(test.doc.getElementById("secret").tagName); /* Alert: "DIV" */
test.destroy();
Run Code Online (Sandbox Code Playgroud)
sanitiseHTML(html)基于我之前创建的replace_all_rel_by_abs(html)功能.<applet>)| 归档时间: |
|
| 查看次数: |
16968 次 |
| 最近记录: |