DVD
DVD

Reputation: 1794

Get content inside script as text

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


}

Upvotes: 40

Views: 90695

Answers (7)

aashish-cd
aashish-cd

Reputation: 1

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.

Upvotes: 0

jcubic
jcubic

Reputation: 66650

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.

Upvotes: 2

Alessandro Battistini
Alessandro Battistini

Reputation: 792

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

Upvotes: 1

vsync
vsync

Reputation: 130750

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

Upvotes: 0

IAMSAMMM
IAMSAMMM

Reputation: 385

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

Upvotes: 26

Vigrond
Vigrond

Reputation: 8198

Just give your script tag an id:

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

http://jsfiddle.net/UBw44/

Upvotes: 27

Abdul Munim
Abdul Munim

Reputation: 19217

Try this:

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

Upvotes: 9

Related Questions