Can I escape html tags within a class (recreate the xmp tag)?

两盒软妹~` 提交于 2019-12-24 21:22:53

问题


A couple ways to think of this question. Decide for yourself which is most useful for you…

  • Can javascript recreate the deprecated <xmp> tag with an "xmp" class?
  • Can we mimic SO's markdown processor's escaping tags within inline code?
  • (metaSO, I admit) How does SO's md processor escape tags in inline code?
  • Can we escape < in markdown code blocks embedded in HTML?

The goal: a class that escapes <, allowing that class to contain the text <html>, <body>, <head>, <script>, <style>, <body>, and any other tags that don't belong inside <body> or are processed specially, without processing them specially.

<xmp> achieved this (and actually continues to - deprecated but still browser-supported): <xmp><body></xmp> was like &lt;body&gt;. SO's markdown processor achieves this in inline code: to display <body> just write `<body>` (which itself is \`&lt;body>\` and cannot be included in an SO code block… I'm not the only one who could use this ;)

My solution so far —replacing all < with &lt;— takes care of the less-special HTML tags (is there a name for these within-<body> static content tags? <div>, <code>, <span>, etc), but the "special" tags still have to be started with &lt; instead of <

Javascript:
xmps = document.getElementsByClassName('xmp');
for (var i = 0; i < xmps.length; i++) {
    var xmp = xmp.item(i);
    var newhtml = xmp.innerHTML.replace(/\&gt;/g,"\>").replace(/\&lt;/g,"\<");
    xmp.innerHTML = newhtml;
    }

With that I can write <div class="xmp">&lt;body></div>.

What will allow

<div class="xmp"><body></div>?

or how about?

<div class="xmp">
    <body>
    &/div>
</div>

The details of my project might matter: There'll be markdown in class="xmp" so we need to be careful with line-initial >s. There is no user input, so security isn't(?) an issue. I'm hoping for a solution that doesn't use jQuery.


回答1:


You cannot create the functionality of the xmp with JavaScript, because the functionality is about HTML parsing. And the element has already been parsed by the browser when it JavaScript can get her hands on it.

On the other hand, I don’t see any need for that. As far as I know, xmp is supported by all browsers, and HTML5 CR requires that support be retained and that new browsers implement it too. It also says that authors must not use it, but this doesn’t mean xmp wouldn’t work.



来源:https://stackoverflow.com/questions/14916975/can-i-escape-html-tags-within-a-class-recreate-the-xmp-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!