Correct handling of escape characters, xss

Hello, I have JS ajax code where users type some test c++ code into a codemirror window… I want to store this server side as JSON. I then want to serve this code back to a page and have it load back into codemirror.

An example of the Javascript/ajax -

var codem1 = CodeMirror(document.getElementById(“mycode”),{…}

var postinfo = {“jscode”:codem1.getValue()}
$.ajax({url: ‘http://domain/’,type: ‘POST’,dataType: ‘json’,data: postinfo})

I can then collect the POST and save it server side.

What are the best practices to load the code back into codemirror safely?

for example, after retrieval from server -

JS example -


How does codemirror handle escape characters etc? Is it possible that during the the parsing into codemirror… some evil code could escape and the JS could be executed client-side?

codemirror does for example convert newline characters “\n” automatically etc.

CodeMirror does not do any kind of escaping or unescaping of its in- and output. So the way you encode the text as you communicate with the server is entirely up to your communication code.

I suppose what I am asking is - can codemirro safely accept any input? Is it safe to load arbitrary text that users have submitted into a codemirror box ?

CodeMirror treats its input (as in the value option) as plain text, and doesn’t do anything unsafe with it. So yes, you can put arbitrary text into it.