1

I need to append the following code via innerHTML to a HTML textfield.

<script type="text⁄javascript"><!--
my_client = "test/test2/456789";
my_num = "gjhklasd";
my_width = 728;
my_height = 90;
my_page_url = "${SOMEURL}";
//-->
</script>

Is there an alternative to escaping above code for JavaScript other than making it look like?

&lt;script type=&quot;text&frasl;javascript&quot;&gt;&lt;&#33; etc.

I'm asking because escaping the snippet with above entities results in "ghost script" to be inserted e.g. <!-- appears all of the sudden at places where I didn't put it.

As aside this might be a Browser Bug I discovered. Reproducable on Firefox 9 for Windows and Opera 11 for Linux.

3
  • Btw, I do not think it is a bug, rather it's a feature :) Commented Jan 17, 2012 at 15:47
  • Maybe I'm missing something but an HTML form input with type "text" cannot have any child nodes (text or elements, afaik) and the form "textarea" input element displays its contents as-is, so there is no need to escape/encode the text. Commented Jan 17, 2012 at 15:48
  • Aside: is escaping Javascript using the comment hack still even necessary? Are any browsers still in use that won't handle a script block without it? Commented Jan 17, 2012 at 15:54

2 Answers 2

1

You could try using the innerText property which should handle the escaping automatically. You'll just have to avoid having the sequence </script> in a string literal in a JavaScript block. (There's an explanation in one of the related questions.) You can work around this for instance by breaking up the tag:

var t = '<script type="text/javascript"><!--\n\
    abc\n\
        --></script'+'>';
elmt.innerText = t; 

jsFiddle: http://jsfiddle.net/pB24u/2/

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

Comments

1

In case you're recieving the HTML as a parameter, or just want have the string with that script look nicer in your code: I'd just use some sort of encoder on the it. Here seems to be one: http://www.strictly-software.com/scripts/downloads/encoder.js

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.