0

I have JS calling remote server through AJAX. The response contains something similar to this

<script>alert(document.getElementById('some_generated_id').innerHTML; ... </script>

User copies the response and uses for own purposes. Now I need to make sure that not a single browser runs the code when I do this:

var response = '<scrip.....';
document.getElementById('output_box').innerHTML = response;

Same should apply to any HTML tags. I know that .text() from jQuery will do exactly what I need:

var response = '<scrip.....';
$('#output_box').text(response);

I am looking for any solutions, including, but not limited to: escaping special characters, however displaying them correctly; adding zero-width space to tags (has to be efficient); outputting in parts. Has to be pure JS.

0

1 Answer 1

1

If you're using a server-side language there is probably a method to escape special characters.

In PHP you could use htmlspecialchars(), it will convert certain characters that have significance in HTML to HTML entities (i.e. & to &). They will still display correctly and you'll be able to copy and paste the text, but the javascript shouldn't run.

If you need a pure javascript solution for this, someone has answered that here https://stackoverflow.com/a/4835406/15000

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I am using server-side, however this has to be done at client. Solution is exactly what I was looking for but could not find.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.