Best practice for embedding arbitrary JSON in the DOM?

后端 未结 7 803
抹茶落季
抹茶落季 2020-11-29 19:58

I\'m thinking about embedding arbitrary JSON in the DOM like this:



        
相关标签:
7条回答
  • 2020-11-29 20:26

    This method of embedding json in a script tag has a potential security issue. Assuming the json data originated from user input, it is possible to craft a data member that will in effect break out of the script tag and allow direct injection into the dom. See here:

    http://jsfiddle.net/YmhZv/1/

    Here is the injection

    <script type="application/json" id="stuff">
    {
        "unicorns": "awesome",
        "abc": [1, 2, 3],
        "badentry": "blah </script><div id='baddiv'>I should not exist.</div><script type="application/json" id='stuff'> ",
    }
    </script>
    

    There is just no way around escaping/encoding.

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