Hacker News new | past | comments | ask | show | jobs | submit login

The browser does not know the path. Also, if the function (or one of its parents) is in a closure, there may not even be a path to the function from window.

If you're sure the function is reachable from window you can search for it recursively:

    (function () {
        function search(prefix, obj, fn, seen = null) {
            if (!seen) seen = new Set();

            // Prevent cycles.
            if (seen.has(obj)) return false;
            seen.add(obj);

            console.log('Looking in ' + prefix);

            for (let key of Object.keys(obj)) {
                let child = obj[key];

                if (child === null || child === undefined) { 
                } else if (child === fn) { 
                    console.log('Found it! ' + prefix + '.' + key); 
                    return prefix + '.' + key;
                } else if (typeof child === 'object') { 
                    // Search this child.
                    let res = search(prefix + '.' + key, child, fn, seen);
                    if (res) {
                        return res;
                    }
                }
            }

            return false;
        }

        // For example:
        let fn = function() { alert('hi'); }
        window.a = {};
        window.a.b = {};
        window.a.b.c = {};
        window.a.b.c.f = fn;
        return search('window', window, fn);
    })();



Yeah it's reachable (in unsafeWindow for user script), I eventually find it by something similar.

In your example, you already has a reference of `fn` to use, which isn't the case for my userscript (if I have a reference, I would just use it!).

I have to search based on the features in plain text of the function (using some regexes on `fn.toString()` to check how the arguments look like).


The idea is that you use a breakpoint somewhere where you have a reference to the function to see it then paste the search() function in the debugger console and call it to find it in window


Oh I got it now. Thanks! Will try next time.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: