Xelariel
Xelariel

Reputation: 1

About innerHTML in JavaScript

Is it safe to use innerHTML to make something like this:

newContent = "";

newContent += "<tr>";
   newContent += "<td>" + data.fullname + "</td>";
   newContent += "<td>" + data.fixedname + "</td>";
   newContent += '<td class="text-center"><button id="id_'+a+'" type="button" class="btn btn-xsmall shadow-none">Button</button></td>';
newContent += "</tr>";

document.getElementById("myID").innerHTML += newContent;

The data I get from ajax.

or this:

newContent = "<i class="fa fa-spinner fa-spin fa-fw"></i> Submitting ...";

document.getElementById("myID").innerHTML = newContent;

If not what can I do to substitute it?

I am trying to use setHTML() instead of innerHTML, but I still don't know if I can replace innerHTML with that.

Upvotes: -1

Views: 76

Answers (1)

asportnoy
asportnoy

Reputation: 2534

It is not safe. This opens you up to a cross-site scripting attack which can, at best, cause your page to be messed up, but at worse, allow an attacker to execute arbitrary code on your website.

In order to make it safe, you need to escape the variable content:

function escapeHtml(unsafe)
{
    return unsafe
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
 }

Run your variable through this function and it should be ok to use.

Upvotes: 1

Related Questions