Dealing with Data that has '<script>" tags in it



  • Hi jsreports,

    I wanted to get your help with what to do when there are <script> tags in the data. It seems to create a strange error.

    I have made a very simplified version of how we use report templates here:

    https://playground.jsreport.net/w/anon/EBcZmEUS

    The template is connected to data, then that data is returned using JSON.stringify() by a global helper function.

    Then in script tags in the template we iterate through the data (usually doing a lot of manipulating and aggregation) and append elements to the report template body.

    If you run the 'testTemplate' with 'testData' selected it works fine.

    If you then change the data to 'testDataScript' you will see that there are <script> tags at line 31. Running the template results in some odd behaviour.

    I am not sure how to remedy this, is there a way to clean the data after it is used in jsreport - say with a library such as he.js - or does the data need to be sanitised in our application back end before it is sent to jsreport?



  • The trouble is that your data contains html, and if you call templating engines {{{toJSON root}}} , it will place inside script another html and that breaks the html structure.

    What you need to do is serialize json with templating engines in a way it doesn't break the html. Like this:

    function toEncodedJSON (data) {
      return encodeURIComponent(JSON.stringify(data));
    }
    

    And then deserialize accordingly:

    const jsonEncoded = "{{{toEncodedJSON root}}}";    
    const total = JSON.parse(decodeURIComponent(jsonEncoded))
    

Log in to reply
 

Looks like your connection to jsreport forum was lost, please wait while we try to reconnect.