⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 objbrowser.js

📁 ie dom 开发的文章
💻 JS
📖 第 1 页 / 共 2 页
字号:
/*

JAVASCRIPT OBJECT BROWSER v3.0 RC (c) 2001-2004 Angus Turnbull. All Rights Reserved.
Visit http://www.twinhelix.com for licensing info and more scripts!
Updated: 2 July 2004


-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

Can index, browse & alter parts of the Document Object Model in a table,
in real time, displaying the names and values of a browser's page objects.
Use this to assist in development -- it's perfect for answering questions
like "How do I find the height of..." when you're writing DHTML. It's a
little rough in places, and may not be able to browse all parts of the DOM.
Your mileage may vary, especially in older/unusual browsers.
   Not all objects seem to be indexed properly, such as document.layers and
document.plugins in NS4, although you can often use the 'Go To' box at the
top of the screen to browse them, try typing "document.layers.0".
   You can also browse through any objects you have created in another page --
again, type in their names -- and functions like "document.getElementById()".
Oh, and find a recent copy of Mozilla to browse, it lists functions of objects
as well as their properties which is very useful indeed :).


Known Issues / Rare and Extraordinary Bugs:

* Under alternative shells (such as LiteStep) or alternative browsers using the
  IE rendering engine (tabbed browsers etc), IE sometimes throws more errors
  than normal when you try to browse some parts of the object hierarchy.
  - Workaround: 'System Integration', huh? Better boot to Explorer and run
    the plain vanilla IEXPLORE.EXE browser UI for best results.

* You can browse another file by opening this page from a window.open() call
  or opening another page from this one. However, once you close that page,
  you cannot browse further as the link between windows is broken.
  - Workaround: Refresh this page after closing the external file. You could
    modify the code to check for 'top.cwn.closed' but then you'd be unable to
    pass object references to the browse function anyway.


I hope you find this useful. Try loading in an IFRAME or similar, as this script
will automatically detect and browse the topmost frameset - this can help you
debug a page you're working on, or just locate those elusive .style properties :).
Also calling via window.open() works well (the script will automatically select
the parent window's topmost frameset to browse), and you can enter a filename
down the bottom which will be opened and browsed from the current script window.
The "window.location" object will of course tell you the file being browsed.


You can add this to the IE context menu by following these steps (Power users
only -- if you aren't familiar with the Registry, skip this):
 1) Open the Registry Editor (Start -> Run -> 'regedit.exe')
 2) Browse to HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\MenuExt
 3) Add a new key called 'Browse DOM' or something similar. Open it.
 4) Set its 'Default' value string to the path to this browser HTML file,
    for example 'c:\stuff\objbrowser.html'.
 5) Add another new 'Binary' value called 'contexts', set to '01'.
 6) Reload IE and try it out.

Otherwise, this script supports activation via bookmarklets, which is probably
more useful as you can browse any domain with the JS file on you hard disk.
Click the link at the bottom of the output for instructions.


Ideas would be welcome on better classification of event handlers. Most are
actually of type 'object' (in IE at least), but some have no type. Currently,
it's called an event handler if it starts with 'on' and is not 'onLine' from IE's
navigator objects. Any ideas as to how this can be improved?

Also, it doesn't work in Opera v5 or 6, as they don't support enumerating built in
objects according to my experiments and their technical docs. Opera 7+ should be OK.
   I had to restrict innerHTML et. al. in IE4 as on my system it generated errors.
That could always be because I have IE5 and IE6 installed as well though (yup, it's
possible, with some DLL wrangling).

I have managed to royally crash IE by browsing some sites with this, so probably
make sure you're not doing anything really important when testing for a start.
You use it entirely at your own risk, on an "as-is" basis with no warranties, etc.


Update History:

v3.0: * Converted main code over to JS file.
      * Added bookmarklet capability, so it can run on foreign domains.
      * Colourised property results by value type (string, number, boolean, other).
      * Wrapped code up in an object, to reduce global vars.
      * Moved bad object lists outside the browse function, and gave the script a
        BIG speed boost when testing properties as they're now associative arrays.
      * Now there's try/catch error checking for object values too.
      * Altered "set property" function to make it more sensible & set proper types.
      * Enabled sorting in all browsers, might as well...
      * Put in a small referencing bug workaround to make it go in Opera 7.
      * Worked around a weird Safari bug I still don't understand.
      * Misc. cleaning up and tweaks, polished HTML output a bit, e.g. now object
        titles are displayed in browser back/forward listing.

v2.1: * Made IE6 sort categories as well, something MS must have forgotten.
      * Built in try/catch error checking in new browsers, for less errors.
      * Fixed altering properties in arrays, e.g. document.all[0].something.
      * Added form to evaluate a JS string in the window being browsed.
      * A general trimming and tweaking.
      * v2.11 Maintenance Release: Fixed frameElement as property crash in IE6,
        also fixed window.fullScreen uncaught exception in Mozilla 1.x.

v2.0  * Passed object reference as well as strings to objBrowse().
      * Slimmed down bad object checking, removed 'restricted' mode.
      * Made it browse collections properly as obj[0] not obj.0
      * Made frame usage much simpler & more reliable.
      * Added a nice 'sorry' error dialog for IE at least.
      * Made NS6 sort categories into alphabetical order.
      * Displays the first 100 chars of an object's value only, makes browsing
        easier and cleaner when big functions are assigned to events.
      * Loads of other tweaks and changes. 

v1.0  * Initial public release.

*/








// Attempt to be courteous even when chronically/perpetually broken.
window.onerror = function(err, file, line) {
 alert('The Object Browser has encountered an internal error,\n' +
  'possibly due to to an unevaluable property.\n\n' +
  'Error in Line ' + line + ': ' + err + '.\n\n' +
  'Property name: ' + JSObj.propName + '\n\n' +
  'Please select a different object to browse, or refresh.');

 return true;
}



// For the rest of the script, I'll wrap up the functions in an object, to stop polluting
// the place with global vars and make something interesting to browse.
// Since there's only one of these, I can't be bothered prototyping it.

window.JSObj = new Object();

// Records the property the script is currently attempting to evaluate.
JSObj.propName = '';

// From where do we start browsing? preObj is a variable that is prepended to any text
// string passed to the object browser. Try and find an opener window, or just a frameset.
JSObj.preObj = (top.opener ? 'top.opener.' : 'top.');


// Some browsers can't detect properties of objects well and crash the script.
// So here are lists of values to skip or force to a particular type.

// window.fullScreen causes problems in some new Mozilla versions, so ignore it entirely.
JSObj.skipProps = { fullScreen:true }


// Some browsers can't reliably detect some types, so preset these property types.
JSObj.forceTypes = { height:'number', innerHTML:'string', innerText:'string',
 outerHTML:'string', outerText:'string', applets:'object', embeds:'object' };


// Depending on the browser, we might want to force some objects' values as they cannot
// be detected by the script normally. IE needs a hand on the following:
if (document.all) JSObj.forceValues = { applets:'[object]', clientInformation:'[object]',
 embeds:'[object]', external:'[object]', history:'[object]', mimeTypes:'[object]',
 navigator:'[object]', opsProfile:'[object]', plugins:'[object]', userProfile:'[object]' };

// NS4 has its own set of dodgy objects. Mozilla is pretty good, though.
if (document.layers) JSObj.forceValues = { applets:'[object]', embeds:'[object]' };






// Takes a string like document.all.0.style and formats to document.all[0].style,
// which makes it evaluable without JS errors.
JSObj.getSafeObj = function(str)
{
 var arr = str.split('.');
 str = '';
 for (var i = 0; i < arr.length; i++)
 {
  if (arr[i] != parseInt(arr[i])) str += arr[i] + '.';
  else str = str.substring(0, str.length - 1) + '[' + arr[i] + '].';
 }
 return str.substring(0, str.length - 1);
}

// Returns a string to be evaluated, wrapped in try/catch blocks in supported browsers.
JSObj.tryString = function(try_str, catch_str)
{
 if (document.getElementById) return 'try{' + try_str + '}catch(err){' + catch_str + '}';
 else return try_str;
}





// Main browsing function, pass it an object name and optionally its reference.
JSObj.browse = function(objText, objRef) { with (this)
{
//alert('JSObj.browse() called with args: ' + objText + ', ' + objRef);

 // *** IF NO REFERENCE, CLEAN UP OBJECTS AND EVALUATE ***
 // Trap leading/trailing spaces, periods etc...
 if (!objRef) while(1)
 {
  // Has this loop wound up with nothing left?
  if (!objText) objText = 'window';

  var badChar = false;

  // Check first char for bad character.
  if ((objText.substring(0, 1) == ' ') || (objText.substring(0, 1) == '.'))
  {
   objText = objText.substring(1);
   badChar = true;
   continue;
  }

  // Check last char for bad character.
  if ((objText.substring(objText.length - 1) == ' ') ||
      (objText.substring(objText.length - 1) == '.'))
  {
   objText = objText.substring(0, objText.length - 1);
   badChar = true;
   continue;
  }

  // First and last chars OK? Might as well go on, any other errors can be refreshed.
  if (!badChar)
  {
   // Why the first eval? I don't know either. Ask the NS4 dev team why it's needed...
   eval('window');
   objRef = eval(getSafeObj(preObj + objText));
   break;
  }
 }


  // *** LOOP & DETECT BAD PROPERTIES, CATEGORISE PROPERTIES INTO ARRAYS ***


 // Multidimensional array to hold 3 classes of names of children/properties etc.
 var Objects = new Array(new Array(), new Array(), new Array());

 // Names of the categories.
 var catNames = new Array('Child Objects','Properties','Event Handlers');

 // We have to actually access some objects to make NS4 show them :).
 if (navigator.appName=='Netscape' && !document.getElementById)
 {
  if (eval(preObj+'screen')) {}
  if (eval(preObj+'navigator')) {}
  if (eval(preObj+'document.layers')) {}
 }

 // The main loop.
 for (propName in objRef)
 {
  //if (objText.indexOf('document') != -1) alert('Categorising: ' + propName);

  var objType = '', aIndex, aRef;

  // Skip displaying some objects.
  if (JSObj.skipProps && JSObj.skipProps[propName]) continue;

  // Some properties cause crashes, so preset them...
  if (JSObj.forceTypes && JSObj.forceTypes[propName]) objType = forceTypes[propName];

  // Well, if it hasn't been ruled out, call typeof()...
  // If the script crashes here, add the property to the JSObj.forceTypes array.
  if (!objType) eval(tryString('objType = typeof objRef[propName]', 'objType = "string"'));


  // Start categorising into arrays... aIndex is the type of propName.

  // Call it an event handler as their objTypes vary, add to end of Objects[2]...
  // I know this is a bit dodgy, anyone know a better way of detecting handlers?
  if (propName.substring && (propName.substring(0, 2) == 'on') && (propName != 'onLine'))
   aIndex = 2;

  // Otherwise add to 'objects' subarray if it reports itself as an object.
  else if (objType == 'object') aIndex = 0;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -