HTML Encoded strings recognized by the javascript engine, how's it possible?

后端 未结 1 445
耶瑟儿~
耶瑟儿~ 2021-01-27 02:48

Well. This night was a very strange night to me. I am sorry to create a new question after creating two other questions previously, but this is another argument at all. If I get

相关标签:
1条回答
  • 2021-01-27 03:37

    Re:

    <textarea id="..." onfocus="windows.alert(&#39;Hello World!&#39;);"></textarea>
    

    There's nothing odd about that (other than your using windows.alert instead of window.alert). It should work fine (and does; example). The HTML parser parses HTML attribute values, and handles processing entities like &#39;. The JavaScript source code it eventually hands to the JavaScript interpreter will have quotes in it. The browser doesn't hand the literal characters & # 3 9 ; to the JavaScript interpreter.

    It's just the same as:

    <input type='text' value="This is a &#39;funny&#39; value too">
    

    The HTML parser processes the entities, and the actual value assigned to the input is This is a "funny" value too.

    Incidentally, this is also why this seemingly-innocent HTML is actually wrong and will fail validation (although most browsers will allow it):

    <a href='http://www.google.com/search?q=foo&hl=en'>Search for foo</a>
    

    More correctly, that should be:

    <a href='http://www.google.com/search?q=foo&amp;hl=en'>Search for foo</a>
    <!--                                       ^^^^^--- difference here   -->
    

    ...because the HTML parser parses the value, then assigns the parsed result to the href attribute. And of course, an & introduces a character entity and so to literally get an & you must use &amp; everywhere in HTML. (Again, most browsers will let you get away with it if what follows the & doesn't look like an entity. But that can and will bite you.)

    0 讨论(0)
提交回复
热议问题