简体   繁体   中英

Is there a simple way in javascript to test for “null or not an object” error in IE8

For a long time, I've trusted a lot of code examples showing supposedly allowed 'safe" detection of unavailable objects or object properties. Two quick examples include getting the available with/height of a screen like this...

var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

Or maybe to make sure a service or procedure was available, so I could take alternate action, examples including...

 if (!window.event) // do something else
 if (!window.XMLHttpRequest) // do something else

I didn't make up any of the above tests, but took them from answers here on stackoverflow, often from high rated answers. Yet when I run code with constructs on this on IE8, The script will stop, and the debugger will spit out errors like...

'window.event' is null or not an object 
'window.XMLHttpRequest' is null or not an object 
'window.innerWidth' is null or not an object

And of course they aren't "warnings'.. they are errors which stop everything. So I guess there is no EASY way to test these kinds of objects or object properties in IE8? I suppose I could put try/catch blocks surround every line of code that might possibly cause a 'null or not an object' complaint, but its definitely going to make my library a lot bigger, and probably slower. And conditional compilation constructs such as this don't seem to work very well...

<!--[if gte IE 9 | !IE ]>-->
 // do something only if !IE or IE > 8
<!--<![endif]>-->
// resume normal inclusion? usually not reliably!

So in the examples I've given that caused the errors, what can I do to make the code safer for browsers that don't support the objects, just using plain vanilla javascript?

Well, since support for the "in" operator stretches all the way back to IE 5.5 (at least according to this MDN reference article: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in ), you might try something like this:

if ('event' in window || 'innerWidth' in window || 'XMLHttpRequest' in window) {

    // Do stuff...

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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