Question

I would like to print the content of a script tag is that possible with jquery?

index.html

<script type="text/javascript">

    function sendRequest(uri, handler)
    {


    }
</script>

Code

alert($("script")[0].???);

result

function sendRequest(uri, handler)
{


}
Was it helpful?

Solution

Just give your script tag an id:

<div></div>
<script id='script' type='text/javascript'>
    $('div').html($('#script').html());
</script>
​

http://jsfiddle.net/UBw44/

OTHER TIPS

You can use native Javascript to do this!

This will print the content of the first script in the document:

alert(document.getElementsByTagName("script")[0].innerHTML);

This will print the content of the script that has the id => "myscript":

alert(document.getElementById("myscript").innerHTML);

Try this:

console.log(($("script")[0]).innerHTML);

You may use document.getElementsByTagName("script") to get an HTMLCollection with all scripts, then iterate it to obtain the text of each script. Obviously you can get text only for local javascript. For external script (src=) you must use an ajax call to get the text. Using jQuery something like this:

var scripts=document.getElementsByTagName("script");
for(var i=0; i<scripts.length; i++){
    script_text=scripts[i].text;
    if(script_text.trim()!==""){ // local script text 
        // so something with script_text ...
    }
    else{ // external script get with src=...
        $.when($.get(scripts[i].src))
            .done(function(script_text) {
              // so something with script_text ...
            });         
    }
}

Printing internal script:

var isIE = !document.currentScript;

function renderPRE( script, codeScriptName ){
  if (isIE) return;
  
  var jsCode = script.innerHTML.trim();
  // escape angled brackets between two _ESCAPE_START_ and _ESCAPE_END_ comments
  let textsToEscape = jsCode.match(new RegExp("// _ESCAPE_START_([^]*?)// _ESCAPE_END_", 'mg'));
  if (textsToEscape) {
    textsToEscape.forEach(textToEscape => {
      jsCode = jsCode.replace(textToEscape, textToEscape.replace(/</g, "&lt")
        .replace(/>/g, "&gt")
        .replace("// _ESCAPE_START_", "")
        .replace("// _ESCAPE_END_", "")
        .trim());
    });
  }
  script.insertAdjacentHTML('afterend', "<pre class='language-js'><code>" + jsCode + "</code></pre>");
}
<script>
// print this script:

let localScript = document.currentScript;

setTimeout(function(){
  renderPRE(localScript)
}, 1000);
</script>


Printing external script using XHR (AJAX):

var src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";

// Exmaple from: 
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
function reqListener(){
  console.log( this.responseText );
}

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", src);
oReq.send();


*DEPRECATED*: Without XHR (AKA Ajax)

If you want to print the contents of an external script (file must reside on the same domain), then it's possible to use a <link> tag with the rel="import" attribute and then place the script's source in the href attribute. Here's a working example for this site:

<!DOCTYPE html>
<html lang="en">
    <head>
       ...
       <link rel="import" href="autobiographical-number.js">
       ...
    </head>
    <body>
        <script>
            var importedScriptElm = document.querySelector('link[rel="import"]'),
                scriptText = scriptText.import.body.innerHTML;

            document.currentScript.insertAdjacentHTML('afterend', "<pre>" + scriptText + "</pre>");
        </script>
    </body>
</html>

This is still experimental technology, part of web-components. read more on MDN

The proper way to get access to current script is document.scripts (which is array like HTMLCollection), the last element is always current script because they are processed and added to that list in order of parsing and executing.

var len = document.scripts.length;
console.log(document.scripts[len - 1].innerHTML);

The only caveat is that you can't use any setTimeout or event handler that will delay the code execution (because next script in html can be parsed and added when your code will execute).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top