Return script content with src attribute

I have a bit of a problem here, and I don’t even know if it is possible at all, here is my dilemma:

I have this script code:

<script id='script1' src='http://link.to.js'></script> 

When using firebug, I can clearly see that the script is loaded bee between these tags, like this

 <script id='script1' src='http://link.to.js'> function something(){ alert('hi');} </script> 

What I want to do, with another script, get the content between these tags, something like

 var x = document.getElementById('script1').innerHtml; document.getElementById('somedividhere').innerHtml = x; 

This works fine WHEN the code is already part of html, and not when it is loaded from src.

I searched for this for several hours and I did not find any hint, hope someone can help me with this.

+4
source share
1 answer

I think Firebug just shows you this for convenience. If you want to get the code from a script, you have to use AJAX.

You can do something like this:

 function ajaxFunction(){ var ajaxRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } // Create a function that will receive data sent from the server ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ var scriptcontent = ajaxRequest.responseText; //Do something with the content } } ajaxRequest.open("GET", document.getElementById('script1').src, true); ajaxRequest.send(null); } 

Just a few notes:

+3
source

Source: https://habr.com/ru/post/1336653/


All Articles