Error Handling for 'console' Undefined in Internet Explorer
When using Firebug, statements like console.log("...") may encounter errors claiming that 'console' is undefined, particularly in Internet Explorer 8 and earlier versions. To resolve this, attempts were made to implement a workaround by adding a script block at the beginning of the page with:
<script type="text/javascript"> if (!console) console = {log: function() {}}; </script>
However, errors persisted. A more effective solution is recommended:
if (!window.console) console = ...
This approach leverages the fact that an undefined variable cannot be accessed directly. Conversely, all global variables exist as attributes of the global context, window in the case of browsers. As a result, accessing an undefined attribute, such as window.console, does not generate an error.
An alternative method to avoid using the global variable window is to employ the typeof operator:
if (typeof console === 'undefined') console = ...
This approach ensures that console is undefined before assigning it a value, effectively suppressing the error.
The above is the detailed content of How to Avoid 'console is undefined' Errors in Internet Explorer?. For more information, please follow other related articles on the PHP Chinese website!