-1

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.

4
  • Are there any errors in the console? In the code you presented, variables are not defined with let or var, is that ok? The second code is syntactically bad because it is trying to describe double quotes within double quotes. Commented Nov 3, 2022 at 2:34
  • newContent = "<i class="fa fa-spinner fa-spin fa-fw"></i> Submitting ..."; <-- This is syntactically invalid JavaScript: you need to escape the double-quotes used for attributes. Put newContent = "<i class=\"fa fa-spinner fa-spin fa-fw\"></i> Submitting ..."; instead. Commented Nov 3, 2022 at 2:35
  • What kind of safety issues are you worried about? Commented Dec 1, 2024 at 12:35
  • <stackoverflow.com/q/11515383/3840170> may be relevant. Commented Dec 1, 2024 at 12:38

1 Answer 1

1

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.

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

9 Comments

To be clear, what is unsafe is only the first snippet they used, and only if they don't trust the data they fetched from AJAX. It's perfectly fine to use innerHTML to compose DOM from a fixed markup like in their second snippet, or even from trusted data.
@Kaiido I'd err on the safe side and escape even if you trust the source. Doesn't hurt anything.
Except if what you expect is HTML maybe?
Well yeah, if you're expecting HTML then you can't escape it like this. But that's not applicable in this case since the variable is inside an attribute.
OP is setting the content of <td> elements, there is nothing telling us they don't expect HTML produced by their backend.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.