How to prevent XSS when using columns.render to render e.g. a link?

How to prevent XSS when using columns.render to render e.g. a link?

johanvjohanv Posts: 1Questions: 1Answers: 0

I have a table that loads its data via ajax, and I want hyperlinks in a column. I did something similar as in the fourth example in the columns.render documentation.

$('#mytable').DataTable({
  'ajax': { /* ... */ }
  'columns': [
    {
      'data': 'label',
      'render': function (data, type, row, meta) {
        return '<a href="' + /* url goes here */ + '"> + data + '</a>';
      }
    }

This works nicely, but it is vulnerable for XSS. If the ajax call returns some malicious html inside the json, there will be troubles. I read about the text helper to prevent such exploits. But is there a way to get data processed by the text helper, before it is used to create the link? I cluelessly tried the following:

$('#mytable').DataTable({
  'ajax': { /* ... */ }
  'columns': [
    {
      'data': 'label',
      'render': function (data, type, row, meta) {
        var sanitized = $.fn.dataTable.render.text(data, type, row, meta);
        return '<a href="' + /* url goes here */ + '"> + sanitized + '</a>';
      }
    }

but that did not work.

Answers

  • allanallan Posts: 63,457Questions: 1Answers: 10,465 Site admin

    That looks very close. Try:

    $('#mytable').DataTable({
      'ajax': { /* ... */ }
      'columns': [
        {
          'data': 'label',
          'render': function (data, type, row, meta) {
            var sanitized = $.fn.dataTable.render.text().display(data, type, row, meta);
            return '<a href="' + /* url goes here */ + '"> + sanitized + '</a>';
          }
        }
    

    The key is that $.fn.dataTable.render.text is a function which returns an object that has rendering functions in it.

    Allan

This discussion has been closed.