We know that, in DOM-Based Attacks, the malicious code is client-side. To prevent this attack developers must be very careful with the type of code used in the browser.

To be more specific, these types of attacks happen when data from a user-controlled source (like user name or redirect URL taken from the URL fragment) reaches a sink, which is a function like eval() or a property setter like .innerHTML, that can execute arbitrary JavaScript code.

There are several methods and attributes which can be used to directly render HTML content within JavaScript. If these methods are provided with malicious input, then an XSS vulnerability could result. For example:

// Attribute: element.innerHTML = "<HTML> Tags and markup"; // Method: document.write("<HTML> Tags and markup");

Instead, one can replace these methods with an attribute like textContent.

// Will add as an actual HTML element. element.innerHTML = "<maliciousHTML>"; // Will render as text on the webpage. element.textContent = "<displaysAsText>";

Ideally, one could take a step further and avoid rendering user input, especially if it affects DOM elements such as the document.url, document.location, or document.referrer.

Lastly, one should validate and sanitize all user input in order to prevent any data manipulation.



In our index.html file, we currently have a line of code within our <script> tags to display the current URI:

document.write("<b>Current URL</b> : " + document.baseURI);

Let’s separate the HTML and JavaScript code. Display the “Current URL” within the <section> tags instead.

  • The text Current URL: should be enclosed in <b> tags.
  • Follow that with a <span> tag that has the id "contentholder". Make sure to leave the content in the <span> tags empty.

Now, set the <span>‘s content equal to document.baseURI.

  • Use the getElementById method to target the <span> with the id "contentholder".
  • Once targeted, append the textContent method to it.
  • Next, make this element’s text content equal to document.baseURI.
  • Once completed, make sure to comment out the original document.write method.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?