39

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)
{


}
hippietrail
  • 15,848
  • 18
  • 99
  • 158
DVD
  • 1,744
  • 3
  • 17
  • 34

7 Answers7

27

Just give your script tag an id:

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

http://jsfiddle.net/UBw44/

Vigrond
  • 8,148
  • 4
  • 28
  • 46
  • 6
    if your script references an src, then it gets tricky. you could do an ajax call then to the script source, or use server-side to get it before the page loads. – Vigrond Feb 17 '12 at 21:30
26

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);
IAMSAMMM
  • 385
  • 3
  • 5
  • 28
    Will return `""` for `` – Gershom Maes Jul 21 '16 at 18:45
  • I think it should be `innerText` instead of `innerHtml` – Luis Vargas Mar 09 '17 at 05:19
  • 2
    @LuisVargas, No, this also doesn't work, I reckon it is because those functions get the contents of the element between the opening and the closing of the tags, and an external script has no content there. – Tim Wachter May 31 '17 at 11:16
  • External tag can be loaded dynamically instead of inline. Then the code will be inserted between opening and closing tags. It works for me. –  Jun 25 '19 at 01:04
  • is there some way to use this method to select script tags that have a specific type attribute? specifically application/ld+json ? And is there some way to select ALL script tag content of that type on an entire page? – user8694-03 Dec 23 '20 at 16:50
9

Try this:

console.log(($("script")[0]).innerHTML);
Abdul Munim
  • 18,869
  • 8
  • 52
  • 61
2

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).

EDIT: Right now the proper way is to use document.currentScript. The only reason not to use this solution is IE. If you're force to support this browser use original solution.

jcubic
  • 61,973
  • 54
  • 229
  • 402
  • 1
    Chrome's developer console was cutting off a long script in the inspector/elements view, and these lines of code worked great to find it and print it to the console where I could copy (then paste) the content: ```for (let i = 0; i < document.scripts.length; i++) { var text = document.scripts[i].innerHTML; if (text.includes('string I am searching for in a script loaded dynamically')){ console.log(text); } }``` – nmz787 Nov 30 '21 at 17:01
1

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 ...
            });         
    }
}
0

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

vsync
  • 118,978
  • 58
  • 307
  • 400
0

If you want to select and display the content of a specific script tag, you can try this.

// here this will select script type having attribute type with value "application/json", you can edit any attribute name and value as per need.

let scriptContent = document.querySelector('script[type="application/json"]');
console.log(scriptContent.innerText)

If you want to get list of all script tags - use querySelectorAll I hope this helps.

aashish-cd
  • 1
  • 1
  • 4