How can I get the content of the file specified as the 'src' of a <script> tag?

Viewed 57709

If I have a script tag like this:

<script
    id = "myscript"
    src = "http://www.example.com/script.js"
    type = "text/javascript">
</script>

I would like to get the content of the "script.js" file. I'm thinking about something like document.getElementById("myscript").text but it doesn't work in this case.

17 Answers

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

Do you want to get the contents of the file http://www.example.com/script.js? If so, you could turn to AJAX methods to fetch its content, assuming it resides on the same server as the page itself.

I don't think the contents will be available via the DOM. You could get the value of the src attribute and use AJAX to request the file from the server.

if you want the contents of the src attribute, you would have to do an ajax request and look at the responsetext. If you where to have the js between and you could access it through innerHTML.

This might be of interest: http://ejohn.org/blog/degrading-script-tags/

.text did get you contents of the tag, it's just that you have nothing between your open tag and your end tag. You can get the src attribute of the element using .src, and then if you want to get the javascript file you would follow the link and make an ajax request for it.

In a comment to my previous answer:

I want to store the content of the script so that I can cache it and use it directly some time later without having to fetch it from the external web server (not on the same server as the page)

In that case you're better off using a server side script to fetch and cache the script file. Depending on your server setup you could just wget the file (periodically via cron if you expect it to change) or do something similar with a small script inthe language of your choice.

I had a same issue, so i solve it this way:

  1. The js file contains something like
window.someVarForReturn = `content for return`
  1. On html
<script src="file.js"></script>
<script>console.log(someVarForReturn)</script>

In my case the content was html template. So i did something like this:

  1. On js file
window.someVarForReturn = `<did>My template</div>`
  1. On html
<script src="file.js"></script>
<script>
new DOMParser().parseFromString(someVarForReturn, 'text/html').body.children[0]
</script>

You cannot directly get what browser loaded as the content of your specific script tag (security hazard);

But

you can request the same resource (src) again ( which will succeed immediately due to cache ) and read it's text:

const scriptSrc = document.querySelector('script#yours').src;
// re-request the same location
const scriptContent = await fetch(scriptSrc).then((res) => res.text());

If you're looking to access the attributes of the <script> tag rather than the contents of script.js, then XPath may well be what you're after.

It will allow you to get each of the script attributes.

If it's the example.js file contents you're after, then you can fire off an AJAX request to fetch it.

It's funny but we can't, we have to fetch them again over the internet.

Likely the browser will read his cache, but a ping is still sent to verify the content-length.

[...document.scripts].forEach((script) => {
  fetch(script.src)
      .then((response) => response.text() )
      .then((source) => console.log(source) )

})

If a src attribute is provided, user agents are required to ignore the content of the element, if you need to access it from the external script, then you are probably doing something wrong.

Update: I see you've added a comment to the effect that you want to cache the script and use it later. To what end? Assuming your HTTP is cache friendly, then your caching needs are likely taken care of by the browser already.

Using 2008-style DOM-binding it would rather be:

document.getElementById('myscript').getAttribute("src");
document.getElementById('myscript').getAttribute("type");

You want to use the innerHTML property to get the contents of the script tag:

document.getElementById("myscript").innerHTML

But as @olle said in another answer you probably want to have a read of: http://ejohn.org/blog/degrading-script-tags/

I'd suggest the answer to this question is using the "innerHTML" property of the DOM element. Certainly, if the script has loaded, you do not need to make an Ajax call to get it.

So Sugendran should be correct (not sure why he was voted down without explanation).

var scriptContent = document.getElementById("myscript").innerHTML;

The innerHTML property of the script element should give you the scripts content as a string provided the script element is:

  • an inline script, or
  • that the script has loaded (if using the src attribute)

olle also gives the answer, but I think it got 'muddled' by his suggesting it needs to be loaded through ajax first, and i think he meant "inline" instead of between.

if you where to have the js between and you could access it through innerHTML.


Regarding the usefulness of this technique:

I've looked to use this technique for client side error logging (of javascript exceptions) after getting "undefined variables" which aren't contained within my own scripts (such as badly injected scripts from toolbars or extensions) - so I don't think it's such a way out idea.

Not sure why you would need to do this?

Another way round would be to hold the script in a hidden element somewhere and use Eval to run it. You could then query the objects innerHtml property.

Related