Search code examples
javascriptjqueryx-editable

Stop <script> being entered through x-editable


We use x-editable for fast edit rows. We have noticed a small bug. When a <script> tag is entered in to the editable input it will be executed.

<div class="test"></div>
$('.edit').editable({
    params: function(params) {
        var data = {};
        data['id']          = params.pk;
        data[params.name]   = params.value;
        return data;
    },
    success: function(response, newValue){
        $(".test").html(newValue); 
        //if newValue will be <script>alert('hello')</scipt>
        // then we see alert message with 'hello'
    }
});

For example, if newValue had a string value of <script>alert('hello')</script>, then we see an alert message appear with 'hello'.

How can we stop this behaviour?


Solution

  • Replace in the input the string "script" with "code"... that way it will be output as "text". something like this maybe...

    $('.edit').editable({
    params: function(params) {
        var data = {};
        data['id']          = params.pk;
        data[params.name]   = params.value;
        return data;
    },
    success: function(response, newValue){
        //gi: Perform a global, case-insensitive replacement:
        newValue = newValue.replace(/script/gi, "code");
        $(".test").html(newValue); 
        //if newValue will be <script>alert('hello')</scipt>
        // then we see alert message with 'hello'
    }
    });
    

    JavaScript String replace() Method