How can I get the content of the file specified as the ‘src’ of a tag?

tl;dr script tags are not subject to CORS and same-origin-policy and therefore javascript/DOM cannot offer access to the text content of the resource loaded via a <script> tag, or it would break same-origin-policy.

long version:
Most of the other answers (and the accepted answer) indicate correctly that the “correct” way to get the text content of a javascript file inserted via a <script> loaded into the page, is using an XMLHttpRequest to perform another seperate additional request for the resource indicated in the scripts src property, something which the short javascript code below will demonstrate. I however found that the other answers did not address the point why to get the javascript files text content, which is that allowing to access content of the file included via the <script src=[url]></script> would break the CORS policies, e.g. modern browsers prevent the XHR of resources that do not provide the Access-Control-Allow-Origin header, hence browsers do not allow any other way than those subject to CORS, to get the content.

With the following code (as mentioned in the other questions “use XHR/AJAX”) it is possible to do another request for all not inline script tags in the document.

function printScriptTextContent(script)
{
  var xhr = new XMLHttpRequest();
  xhr.open("GET",script.src)
  xhr.onreadystatechange = function () {
    if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
      console.log("the script text content is",xhr.responseText);
    }
  };
  xhr.send();
}
Array.prototype.slice.call(document.querySelectorAll("script[src]")).forEach(printScriptTextContent);

and so I will not repeat that, but instead would like to add via this answer upon the aspect why itthat

Leave a Comment