Javascript Injection and document.write() - ΩJr. Software Articles and Products

This information lives on a web page hosted at the following web address: 'https://omegajunior.globat.com/code/'.

Why using document.write() in javascript is a bad habit. With test cases.

A.E.Veltstra
2007-09-13, 2014-02-11

I will present 2 test cases which try to use unobtrusive javascript to inject a foreign javascript (such as hosted by advertisement and statistics services). Injecting the script itself is no problem (1st test case). However, if the foreign javascript contains document.write() statements, some current browsers go awry (2nd test case).

The problem lies in a combination of factors, one of which is the content mime type (application/xhtml+xml or text/html) and another is the way the document.write() statement is being abused.

Hopefully these test cases will show why authors should refactor their code to remove document.write() and replace it with methods like document.appendChild().

Because content mime type is involved, the tester page can be opened in 2 modes:


The tester page will describe both test cases and let you control when each test is run. Your browser will need to have javascript activated for these tests.

Test Results

Tested on MS Windows 2003 Server and XP Professional

Content delivered as text/html instead of application/xhtml+xml, distinction made by querying HTTP_ACCEPT header.
BrowserTest case 1Test case 2 as application/xhtml+xmlTest case 2 as text/html
Safari 3 BetaFails *Succeeds: shows nothing, but may mistakenly assume javascript is disabled **Fails: overwrites current document
Opera 10.5 Pre-AlphaSucceedsFails: overwrites current documentFails: overwrites current document
Opera 9.5 AlphaSucceedsSucceeds: shows nothingFails: shows nothing
Opera 9.23SucceedsSucceeds: shows nothing, but may mistakenly assume javascript is disabledFails: shows nothing
K-Meleon 1.02SucceedsSucceeds: shows nothingFails: overwrites current document
Internet Explorer 7SucceedsNot applicableFails: shows nothing and may get stuck in endless loop
Internet Explorer 6SucceedsNot applicableFails: shows nothing
Firefox 3 AlphaSucceedsSucceeds: shows nothingFails: shows nothing
Firefox 2.0.0.6SucceedsSucceeds: shows nothingFails: overwrites current document
*Succeeds when content delivered as text/html instead of application/xhtml+xml.
**Script support recognised correctly when content delivered as text/html.

Need problem solving?

Talk to me. Let's meet for coffee or over lunch. Mail me at “omegajunior at protonmail dot com”.