问题
Is there a way to search for a JavaScript attribute (e.g. a named function) in the currently live object model (what Firebug displays on the 'DOM' tab, I couldn't find a direct equivalent in the Chrome Developer Tools) of the currently loaded page, using the common developer tools of the main browsers?
An example would be that I search for 'beta' and the developer tools show me something like window.alpha.beta
, meaning that some script file has created an object named 'alpha' on the window object, which has an attribute beta.
I explicitly do not want to search for strings in all script files (e.g. Ctrl-Shift-F
in the Chrome Developer Tools).
The use case is that I want to call a function of the page from an extension/userscript. I know the function exists, but it is created using a complex framework and I can't tell where in the page's object model it ends up.
PS: Terminology-related edits of the question are welcome.
回答1:
Loading https://github.com/angus-c/waldo and using it from the console looks like it should do the trick. A little more complex but also tool-agnostic.
回答2:
I wrote up the recursive type function I mentioned in the comment as an anonymous function
(function(searchTerm, parent, parentStr, depthLeft, parentsArr){
var p = parent || window,
child, cObj = null,
s = parentStr || '',
r = [],
d = (depthLeft > 0 ? depthLeft-1 : 5),
pArr = parentsArr || [p];
for( child in p ){
cObj = p[child];
if ( child === searchTerm ) r[ r.length ] = (s+'.'+child).slice(1);
if( d > 0 && cObj !== null && p.hasOwnProperty(child) && typeof cObj === 'object' && cObj !== p && pArr.indexOf(cObj) === -1 )
r = r.concat( arguments.callee( searchTerm, cObj, s+'.'+child, d, pArr.concat([cObj]) ) );
}
return r;
})('createElement');
Last line means will search for .createElement
, starting from window
.
The deeper you go, the longer it will take.
回答3:
If the function is global, you can call it from a userscript using this constructor:
var global = new Global(); // Initialize the Global constructor
// Some code
var globalVar = global.get('variableName'); // Assign the global variable 'variableName' to the local variable 'globalVar'
Because closures cannot be called from the global scope, you will have to use string searching to get any of those (as far as I know).
回答4:
The only way I can think of is by parsing your scripts and using regular expressions to avoid strings and other cases you may not want.
来源:https://stackoverflow.com/questions/12438175/finding-javascript-function-in-the-global-scope