Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 635
Markus Johansson Avatar asked Sep 29 '08 12:09

Markus Johansson


1 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

like image 55
humanityANDpeace Avatar answered Sep 20 '22 13:09

humanityANDpeace