textarea does not accept </script> as text

Asked

Viewed 66 times

2

In the code below I have an error, because javascript understands that I want to close the script tag even if it is in quotes. I am creating a small editor and works perfectly as long as the text does not have </script>. How can I pass </script> so that javascript understands how text?

echo("<script>window.parent.document.getElementById(\"id_textarea\").value=\"</script>\";</script>");

  • Try to put backslash before opening and closing the script tag, like "</script>"

  • Ideal for tags is to use &lt; for < and &gt; for >. That in itself prevents it from being interpreted as code

  • It didn’t because it appears &lt in the code, and I need it to appear normally, unless I’m doing something wrong. Thank you

1 answer

1

This is a very particular case of the text being put on textarea. Notice that when you try to put the </script> doesn’t work:

document.getElementById("id_textarea").value="</script>";
console.log("outro código em JS");
<textarea id="id_textarea"></textarea>

But if it happens to be a zipper </div> already works:

document.getElementById("id_textarea").value="</div>";
console.log("outro código em JS");
<textarea id="id_textarea"></textarea>

It turns out that the JS interpreter itself scans the code until it catches one </script> and ends up finding the one that is as text, ending earlier than it should. Can solve easily by escaping the bar:

document.getElementById("id_textarea").value="<\/script>";
//                                             ^--- escapar a barra
console.log("outro código em JS");
<textarea id="id_textarea"></textarea>

In your code, with PHP would be:

echo('<script>window.parent.document.getElementById("id_textarea").value="<\/script>";</script>');

Note that I changed the beginning of echo for simple quotes in order to simplify and not to be necessary to escape so much stuff.

What I mentioned as a comment works well if the content is to be placed on another kind of labels, such as a <div> for example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.