How to collect all script tags of HTML page in a variable
html, html-parsing, javascript
Solution
To get a list of scripts you can use
- `document.getElementsByTagName("script");` by tag
- `document.scripts;` Built-in collection
- `document.querySelectorAll("script");` by selector
- `$("script")` jQuery by selector
var scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].src) console.log(i, scripts[i].src)
else console.log(i, scripts[i].innerHTML)
}
// To get the content of the external script
// - I use jQuery here - only works if CORS is allowing it
// find the first script from google
var url = $("script[src*='googleapis']")[0].src;
$.get(url,function(data) { // get the source
console.log(data.split("|")[0]); // show version info
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
console.log("Inline script");
</script>
<script>
function bla() {
console.log("Other inline script");
}
</script>
Problem
I would like to collect all the `<script> ....</script>` code section present in the HTML page in some variable. What should be the simpler way to do this, Any idea how it can be retrieved using JavaScript.?? Any help will be greatly appreciated.