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?


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

serializedRecipientOptions =

VF Page

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

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);
            return escapedRecipientList;

Any ideas?

2 Answers 2


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

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

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

  • 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
    Jul 25, 2016 at 20:59
  • 1
    I think you may be right regarding security review.
    – Alan Morey
    Jul 25, 2016 at 21:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.