3

I select a list of sObjects in my controller then pass directly to my visualforce page where I render out as a javascript object. I can't use JSENCODE in the visualforce page because I need the serialized object to be rendered as a JS Object. Instead, I think I need to iterate through the values in Apex and make sure they are encoded to protect against XSS. Any recommendations on the proper way to do this?

Controller

    recipientList = Database.query('select Id, Name, Email from Contact where AccountId=\'' + String.escapeSingleQuotes(originObjectIdString) + '\' and Contact.Name!=Null and Contact.Email!=Null');

serializedRecipientOptions =
JSON.serialize(recipientList);

VF Page

<script type='text/javascript'>
var myEscapedObject = {
serializedRecipientOptions: {!
serializedRecipientOptions}
}
</script>

I was thinking something like this in the controller code (except this doesn't work because JSENCODE is not defined in the controller)

List<sObject> escapedRecipientList = new List<sObject>();
            for(sObject ind_recipient:recipientList){
                ind_recipient.Id = JSENCODE(ind_recipient.Id);
                ind_recipient.Name = JSENCODE(ind_recipient.Name);
                ind_recipient.Email = JSENCODE(ind_recipient.Email);
                escapedRecipientList.push(ind_recipient);
            }
            return escapedRecipientList;

Any ideas?

2 Answers 2

9

You can use JSENCODE in tandem with the built-in Javascript method JSON.parse.

var myEscapedObject = JSON.parse("{!JSENCODE(serializedOptions)}");
0
0

The Apex method String.escapeEcmaScript will allow you to escape text using Javascript (EcmaScript) rules.

2
  • 4
    Won't security review flag it if you don't escape on the client side, regardless of if you use this method? Just curious.
    – Adrian Larson
    Commented Jul 25, 2016 at 20:59
  • 1
    I think you may be right regarding security review.
    – Alan Morey
    Commented Jul 25, 2016 at 21:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .