简体   繁体   English

如何获取网页 HTML 可用的所有 JavaScript 功能?

[英]How to get all JavaScript functions available to the webpage HTML?

I am wondering whether it is possible to get all the JavaScript functions that are included in the HTML.我想知道是否可以获得 HTML 中包含的所有 JavaScript 函数。 For example, if my HTML includes the following:例如,如果我的 HTML 包括以下内容:

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

How do I use JavaScript to retrieve all the JS functions available to this webpage.如何使用 JavaScript 检索此网页可用的所有 JS 函数。 In this case, I would need to retrieve foo , bar and all the functions defined in https://www.example.com/script.js .在这种情况下,我需要检索foobarhttps://www.example.com/script.js中定义的所有函数。 Doing document.getElementsByTagName("script");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.仅将脚本作为 HTML 对象返回,但我需要获取 HTML 中包含的每个脚本的所有函数。 Can this be done?这可以做到吗?

You could iterate on the window object and detect all functions like this:您可以在 window object 上迭代并检测如下所有函数:

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>

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

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