More JavaScript interacting with the DOM

This web page contains some JavaScript code that interacts with the DOM. View the page source in a separate window to see this JavaScript code while you play around with it.

Rewriting an HTML page in the browser using JavaScript

The button below uses the function document.write to rewrite the entire content of the current web page loaded in your browser.

A nicer demo of rewriting an HTML page in the browser using JavaScript

A bit nicer is the button below, which only rewrites part of the content of your webpage, namely the paragraph with the tag demo just above

A small paragraph of text, with the tag demo.

FOR YOU TO TRY: Look at the HTML source to see how that is done.

Inspecting the URL with JavaScript

Below we use JavaScript to extract the URL from the DOM, and write it back inside the web page. You can test that this works by adding superfluous parameters to the URL, e.g. ?name=john, or adding a fragment at the end of the URL, e.g. #demo, which should then be displayed below when you load this new URL. For example, click here.

The URL of this page is:

With JavaScript we can now also extract parameters from the URL (using URLSearchParams)

    The parameter name has the value:
    The parameter uid has the value:
    The fragment part of the URL is:

FOR YOU TO TRY: Edit the URL in the address bar of your browser to add uid and name parameters or a so-called fragment part, i.e. make it a URL of the form http://www.cs.ru.nl/~erikpoll/websec/demo/demo_DOM2.html?name=john&uid=1234#someFragment.

Client-side security risks of URL parameters

Client-side processing of parameters in the URL as we do above is not without security risks. An attacker could try to create a malicious URL with a 'poisoned' parameter in the URL that, when processed in the browser JavaScript, results in XSS. An example is shown in XSS_via_the_DOM. (Of course, malicious parameters in the URL can also cause all kinds of security problems server-side, such as path traversal or SQL injection.)

Server-side, a web application can check for malicious parameters and then remove or sanatise them; it could also reject the entire HTTP request if there malicious parameters in the URL. One exception here is the fragment part of a URL, i.e. the optional part of the URL after the # character. The fragment in the URL is not sent to the server; it is only processed locally in the client, where it is used to specify an offset, a so-called anchor, within a webpage. Fortunately, in that case it will not be executed as JavaScript, so a malicious fragment containing JavaScript can't be used to executed as JavaScript by the browser. (JavaScript in a webpage can inspect and use the fragment in any way it wants, in which case a malicious fragment could lead to XSS, but it very unusual to do this).