0

I currently have a Tampermonkey script with a series of contextualized functions that I provide as options to run when on a certain page.

A simplified version of my code would be:

window.func1 = function func1() {...}
window.func2 = function func2(a) {...}
window.func3 = function func3(a, b) {...}

I would like to have some function that could take the current script I have and provide me with a list of the available functions, something along the lines of:

>> getAvailableFunctions()
<< func1, func2, func3

I have been investigating with the Object.getOwnPropertyNames method, but I can't seem to pull that one out with Tampermonkey.

Can I have some input?

Thank you!

ggonmar
  • 760
  • 1
  • 7
  • 28
  • 4
    You'd probably be better off create an object on `window`, then adding your functions to that object. Otherwise, you're going to get all of the functions on `window`, which include things like `alert`, `confirm`, etc. – Heretic Monkey May 24 '19 at 18:19
  • Actually I've ended up applying what pswg recommended. Despite having all the objects within window, I could apply a filter to retrieve the specific functions I needed by parsing the insides of each of them with a .filter( a=> (typeof(a[1] ==="function" &&& a[1].toString().includes("Comment that identifies"))) – ggonmar May 24 '19 at 18:52

1 Answers1

0

You could try something like this:

Object.entries(window).flatMap(([k, v]) => typeof v === "function" ? k : [])

Object.entries gets an array of key-value pairs, and flatMap here serves as a combined filter + map. This would be equivalent to:

Object.entries(window).filter(a => typeof a[1] === "function").map(([k]) => k)

You might also try excluding native functions like this (tested on FF and Chrome):

Object.entries(window)
  .flatMap(([k, v]) => typeof v === "function" && !/{\s*\[native code]\s*}/.test(v) ? k : [])
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • 1
    It'll list dozens (actually, hundreds in Tampermonkey's sandbox) of standard functions defined in `window`. – wOxxOm May 24 '19 at 18:18
  • ...even with `[native code]` excluded there'll be dozens of standard irrelevant functions. – wOxxOm May 25 '19 at 04:54