Best practice for embedding arbitrary JSON in the DOM?

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

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



        
7条回答
  •  忘掉有多难
    2020-11-29 20:19

    See Rule #3.1 in OWASP's XSS prevention cheat sheet.

    Say you want to include this JSON in HTML:

    {
        "html": ""
    }
    

    Create a hidden

    in HTML. Next, escape your JSON by encoding unsafe entities (e.g., &, <, >, ", ', and, /) and put it inside the element.

    
    

    Now you can access it by reading the textContent of the element using JavaScript and parsing it:

    var text = document.querySelector('#init_data').textContent;
    var json = JSON.parse(text);
    console.log(json); // {html: ""}
    

提交回复
热议问题