12

I've come across this message in JSLint...

document.write can be a form of eval.

and was wondering exactly how so?

The JSLint instructions page states:

The eval function...provide access to the JavaScript compiler. This is sometimes necessary, but in most cases it indicates the presence of extremely bad coding....

So, how does document.write "provide access to the JavaScript compiler" then?

Thanks

James Wiseman
  • 29,946
  • 17
  • 95
  • 158

1 Answers1

14

What does your browser do with this?

document.write('<script type="text/javascript">window.alert("evaled " + (1 + 2))</script>');
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • @Rocket: Seems I'm a little out of date, the `type` attribute is now preferred. But deprecated or not, it works. – Ben Voigt Mar 30 '11 at 18:06
  • 1
    @Ben: Yes, it works, but that's probably because browsers are ignoring the `language` attribute in the first place. – gen_Eric Mar 30 '11 at 18:07
  • @Rocket: Is this the correct modern equivalent? I only dabble in DHTML. – Ben Voigt Mar 30 '11 at 18:13
  • @Ben: Yup, that's correct. :-) In HTML5, the type isn't even needed JavaScript is assumed. – gen_Eric Mar 30 '11 at 18:18
  • Back on topic - Think I understand. The `document.write` is itself writing out JavaScript which is then accessing the compiler. Condensing it down `document.write('');` is therefore broadly equivalent to `alert(eval(1+2));` – James Wiseman Mar 31 '11 at 07:05
  • @James: It's closer to `eval(alert(1+2))`. `document.write` isn't just doing math, it's accessing browser objects, can define functions, etc. – Ben Voigt Apr 01 '11 at 12:49
  • So how do we get it past the Pedantic JS Lint? var iframe = document.createElement('IFRAME'); iframe.setAttribute('src', domain); document.write(iframe); – Will Hancock Oct 22 '12 at 11:08
  • @WillHancock, It's not pedantic in this case. It is warning specifically about a potential vulnerability in your code that could enable, for instance, XSS attacks. Perhaps you know that, and know that your particular usage is safe. In which case you can disable the check for a specific line with `jshint ignore:[...]` comments (e.g. `// jshint ignore:line` at the end of your `document.write` line) – eyelidlessness Dec 13 '15 at 05:07