简体   繁体   English

获取脚本中的内容作为文本

[英]Get content inside script as text

I would like to print the content of a script tag is that possible with jquery?我想打印脚本标签的内容是否可以使用 jquery?

index.html索引.html

<script type="text/javascript">

    function sendRequest(uri, handler)
    {


    }
</script>

Code代码

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

result结果

function sendRequest(uri, handler)
{


}

Just give your script tag an id:只需给你的脚本标签一个 id:

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

http://jsfiddle.net/UBw44/ http://jsfiddle.net/UBw44/

You can use native Javascript to do this!您可以使用本机 Javascript 来执行此操作!

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":这将打印具有 id => "myscript" 的脚本内容:

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

试试这个:

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.您可以使用 document.getElementsByTagName("script") 获取包含所有脚本的 HTMLCollection,然后对其进行迭代以获取每个脚本的文本。 Obviously you can get text only for local javascript.显然,您只能获取本地 javascript 的文本。 For external script (src=) you must use an ajax call to get the text.对于外部脚本 (src=),您必须使用 ajax 调用来获取文本。 Using jQuery something like this:使用 jQuery 是这样的:

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):使用 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) *已弃用*:没有 XHR(又名 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.如果要打印外部脚本的内容(文件必须位于同一个域中),则可以使用带有rel="import"属性的<link>标记,然后将脚本的源放在href属性中。 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 .这仍然是实验性技术,是web-components 的一部分。 read more on MDNMDN上阅读更多

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.访问当前脚本的正确方法是document.scripts (它是类似于HTMLCollection数组),最后一个元素始终是当前脚本,因为它们按照解析和执行的顺序被处理并添加到该列表中。

 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).唯一需要注意的是,您不能使用任何会延迟代码执行的 setTimeout 或事件处理程序(因为可以在代码执行时解析和添加 html 中的下一个脚本)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM