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

571 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

For the <img> question, and how does the browser know it has to fetch new resources, that's simply what does the HTMLImageElement when its src property is set.
It doesn't matter when this happens, and the element doesn't even have to be appended in the document; when you set this src, its fetch algorithm will kick in.

For the cross-origin question, this neither has no relation with when the request is made. But to clarify an other misconception, cross-domain restrictions are here to avoid scripts being able to access cross-domain data, but you can still very well display cross-domain data in your page. And here, since you didn't set the cross-origin attribute of your <img>, then you won't be able to access the content of this image.