Here it is the concept of this article

1. Get JSON from server.
2. The JSON data can have tags like <script>, <div>, <td>...etc.
3. Show the data in a table by preventing XSS attack

Here attacker entered address as "<script>alert('This is XSS attack');</script>". Whenever you showed this in HTML page you will see an alert "This is XSS attack"
But we should not execute the code in the address field. We have to show it as text.

The hackers will give markup text as input to :
      destroy your website User Interface.
      steal your data.
      steal user's cookies ( Stealing authentication ).

"firstName":"John" , 
"address":"<script>alert('This is XSS attack');</script>"

JavaScript :

String.prototype.encodeHtml = function() {
var tagsToReplace = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;'
return this.replace(/[&<>]/g, function(tag) {
return tagsToReplace[tag] || tag;

String.prototype.decodeHtml = function() {
var tagsToReplace = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>'};
return this.replace(/[&<>]/g, function(tag) {
return tagsToReplace[tag] || tag;

jQuery Code to display JSON as content :

  var json = data;
  var eHtml="<table><tr><td>First Name</td><td>"+
       "</td></tr><tr><td>Last Name</td><td>"+

Demo without Encoding :
In this demo you can see the alert box. It means it is executing the script in the address field. 

Demo with Encoding :
In this demo you wont see any alert box. It means it is showing the script as text.
DEMO - Without Encoding DEMO - With Encoding


  1. It's very useful article with inforamtive and insightful content and i had good experience with this information. We, at the CRS info solutions ,help candidates in acquiring certificates, master interview questions, and prepare brilliant resumes.Go through some helpful and rich content Salesforce Admin syllabus from learn in real time team. This Salesforce Development syllabus is 100% practical and highly worth reading. Recently i have gone through Salesforce Development syllabus and Salesforce Admin syllabus which includes Salesforce training in USA so practically designed.

  2. Great Article android based projects

    Java Training in Chennai Project Center in Chennai Java Training in Chennai projects for cse The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training Project Centers in Chennai



Popular Posts