0

I want to parse tags like and into document.body.innerHTML (see below). However although you can do this in Chrome, it doesn't work in IE.I have to get it to work in IE butit seems that isn't possible. Any ideas?

html = '<script> function myFunction() { alert(); } </script>AAA'

doc.body.innerHTML = html

AAA is stored in doc.body.innerHTML

To quickly replicate the issue just add the first line below to the IE console window then see what is in document.body.innerHTML and you will notice its been stripped.

We use a 10 year old text editor which will only work in IE and has always stripped javascript so now I've discovered why and was hoping someone could provide an alternative...googling isn't helping much

document.body.innerHTML = "<script> function myFunction() { alert(); } </script>AAA"

document.body.innerHTML

"AAA"

insanepaul
  • 187
  • 2
  • 5
  • 17

2 Answers2

1

This will work on any browser to insert javascript:

var newScript = document.createElement('script');
var scriptTag = document.getElementsByTagName('script')[0];
newScript.text = "function myFunction() { alert(); }"
scriptTag.parentNode.insertBefore(newScript, scriptTag);
Ramesh
  • 4,223
  • 2
  • 16
  • 24
  • This really doesn't help my issue. I'm using a proprietary text editor written 10 years ago which heavily uses javascript. The piece of code in the question is where it fails. If I was able to store the script tag, image tag etc into document.body.innerHTML like in chrome then all would be fine – insanepaul Nov 14 '13 at 10:31
  • http://stackoverflow.com/questions/1068517/why-cant-i-add-a-string-containing-a-script-tag-to-innerhtml-in-ie - Try this – Ramesh Nov 14 '13 at 10:38
  • Thanks for the link..I tried the DEFER attribute of the Script tag but it didn't work. So it looks like it is by design in MSDN. However any tagged item gets removed eg – insanepaul Nov 14 '13 at 12:22
1

Hi try like below code might help u out..

you need to use escape char for the </script> tag

div.innerHTML = '<script> function myFunction() { alert(); } <\/script>AAA';
codebreaker
  • 1,465
  • 1
  • 12
  • 18
  • The raw text is retrieved from document.getElementById('pinEditHtml').contentWindow.document. – insanepaul Nov 14 '13 at 11:57
  • codebreaker has a correct solution. When ever parser meets a literal ``, it stops parsing current script. You need to manipulate your string before adding it to HTML, or use Ramesh's answer. – Teemu Nov 14 '13 at 17:13