40

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


}

7 Answers 7

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/

Sign up to request clarification or add additional context in comments.

1 Comment

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

5 Comments

Will return "" for <script type="text/javascript" src="path/path/file.js"></script>
I think it should be innerText instead of innerHtml
@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.
External tag can be loaded dynamically instead of inline. Then the code will be inserted between opening and closing tags. It works for me.
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?
9

Try this:

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

1 Comment

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

The proper way is to use document.currentScript. The only reason not to use this solution is IE. If you're forced to support this browser, use the original solution below.

console.log(document.currentScript.innerHTML);

Original solution

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

1 Comment

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

Comments

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

1 Comment

As of February 2019, your MDN link says this is a deprecated feature.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.