How to get all JavaScript functions available to the webpage HTML? - Stack Overflow

I am wondering whether it is possible to get all the JavaScript functions that are included in the HTML

I am wondering whether it is possible to get all the JavaScript functions that are included in the HTML. For example, if my HTML includes the following:

<script src=".js"></script>
<script>
  function foo() {}
  function bar() {}
</script>

How do I use JavaScript to retrieve all the JS functions available to this webpage. In this case, I would need to retrieve foo, bar and all the functions defined in .js. Doing document.getElementsByTagName("script"); only returns the scripts as HTML objects, but I need to get all the functions for each script included in the HTML. Can this be done?

I am wondering whether it is possible to get all the JavaScript functions that are included in the HTML. For example, if my HTML includes the following:

<script src="https://www.example./script.js"></script>
<script>
  function foo() {}
  function bar() {}
</script>

How do I use JavaScript to retrieve all the JS functions available to this webpage. In this case, I would need to retrieve foo, bar and all the functions defined in https://www.example./script.js. Doing document.getElementsByTagName("script"); only returns the scripts as HTML objects, but I need to get all the functions for each script included in the HTML. Can this be done?

Share asked Dec 5, 2020 at 2:18 Mark NibuhMark Nibuh 411 silver badge2 bronze badges 1
  • "Can this be done?" Yes, but it is extremely hard to do so. You'd need to get all of the script tags' innerHTML if it has no src, but if it does, you'd need to use fetch() with that url and get the text response. One you get all of that, you'd need a JS parser to find every single function declaration and modifications to window. – Samathingamajig Commented Dec 5, 2020 at 2:30
Add a ment  | 

1 Answer 1

Reset to default 5

You could iterate on the window object and detect all functions like this:

var list = [];
for (let i in window) {
    if (typeof(window[i]) === "function")
        list.push(i);
}
console.log(list)

By doing this around your script, we can detect functions that were added in-between.

<script>
var list1 = [];
for (let i in window) {
    if (typeof(window[i]) === "function")
        list1.push(i);
}
</script>

<script>
// The script to measure
function newFunction() {}
</script>

<script>
var list2 = [];
for (let i in window) {
    if (typeof(window[i]) === "function")
        list2.push(i);
}
let functionList = list2.filter((item) => {return list1.indexOf(item) == -1})
console.log(functionList.join(" "));
</script>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745069742a4609473.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信