javascriptbrowserdynamic-contentcross-site

Will the browser fetch new resources when you change the DOM with javascript?


I have the following in the HTML body of a page:

   <aside id="ADVERT">
      <img src='https://www.blackstone.com/images/default-source/assets/logos/blackstone-logo.png'>
   </aside>

Later in the page, there is a button that, when clicked, switches the img with another. Here is the button code:

   <button onclick="switchadvert();">Switch Logo</button>

This switchadvert Javascript function is simplicity itself, just one line, using the innerHTML property:

   function switchadvert()
   { document.getElementById("ADVERT").innerHTML = "<img src='http://www.redstone.com/gfx/logo.png'>";
   }

This all appears to work. When I click the button, the logo changes from the Blackstone Group's logo to Redstone's logo.

My question is how does this work, and why does it work?

HOW: Apparently, as soon as I update the DOM with this new innerHTML, the browser realizes this part of the page requires a resource it does not have (the redstone logo) and goes and fetches it? Long after the page has loaded?

WHY: I thought that even if I went to the trouble of doing an AJAX call, to an XMLHttpRequest object, I was not allowed to go get resources from another site after the page has loaded. But here it is doing it without any calls! Doesn't this open the door for cross-site scripting abuse?


Solution

  • TL;DR:

    In today's browsers there should be no treat to XSS by loading an image

    When it comes to fetching data there is a rule called CORS that comes into play.

    CORS only allows certain methods with a few allowed headers without additional configuration on the server end.

    When it comes to images, the browser will fetch (GET) the url, which it allows by CORS and then determine its content type, either by looking at the Content-Type header or some other processes.

    Assuming the source is not affected by XSS and if it's a valid image, it will display it and if not throw an error, but the browser will never execute any javascript inside the browser so there is no threat to XSS. You can test this by having an image source set to a javascript file.