[英]Safely inject html string into <pre> tag keeping syntax highlighting intact
I have string
containing json
data built dynamically with some html
inserted for syntax highlighting. 我有包含
json
数据的string
是动态生成的,并插入了一些html
以突出显示语法。
console.log(highlightedJson);
{
<span class="key">"time":</span> <span class="string">"11:09:09 PM"</span>,
<span class="key">"milliseconds_since_epoch":</span> <span class="number">1406070549038</span>,
<span class="key">"date":</span> <span class="string">"07-22-2014"</span>
}
Styling to be applied to classes: 适用于类的样式:
pre {
outline: 1px solid #ccc;
padding: 5px;
margin: 5px;
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
}
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
Trying to inject this as html
into a <pre>
dom element .. 尝试将其作为
html
注入到<pre>
dom元素中。
var pre = document.createElement('pre');
// also tried this, but again, syntax highlighting is not rendered
//pre.appendChild(highlightedJson));
pre.appendChild(document.createTextNode(highlightedJson))
document.getElementById("body").appendChild(pre);
When this code runs, the string is appended to <pre>
, but syntax highlighting is not showing. 运行此代码时,该字符串将附加到
<pre>
,但不会显示语法高亮。
pre.innerHTML = highlightedJson;
pre.innerHTML = highlightedJson;
gets the result I'm after but this html injection method is discouraged in firefox addons. jquery
jquery
Can anyone suggest an approach? 谁能建议一种方法?
You can try this which is used for innerHTML problems with IE. 您可以尝试将其用于IE的innerHTML问题。 It might also be useful for this situation.
对于这种情况,它也可能有用。
function stringToHTML(str){
var frag = document.createDocumentFragment(),
div = document.createElement('div');
div.innerHTML = str;
while(div.firstChild){
frag.appendChild(div.firstChild);
}
return frag;
}
var pre = document.createElement('pre');
pre.appendChild(stringToHTML(highlightedJson));
document.getElementById("body").appendChild(pre);
This is my suggestion because of your requirement of a string being converted to render-able html. 这是我的建议,因为您需要将字符串转换为可渲染的html。 Because you can't just have html from a string innerHTML is the best bet, but because of security implications I see this as an alternative.
因为您不能仅仅从字符串innerHTML获得html是最好的选择,但是由于安全方面的考虑,我将其视为替代方法。 If you need to you can run checks in the while loop to exclude tags you don't want, or just white list your span tags.
如果需要,可以在while循环中运行检查以排除不需要的标签,或者仅将范围标签白名单。
If you really need the security try html parser then. 如果您确实需要安全性,请尝试html解析器 。 Google about this stuff.
Google关于这个东西。
var htmlStr = '<div><span style="color:#FF0;">h</span>ello</div>';
var range = document.createRange();
var anyElement = document.body;
range.selectNode(anyElement);
var docFrag = range.createContextualFragment(htmlStr);
document.body.appendChild(docFrag);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.