Console Log Cross-browser Compatibility


/ Published in: JavaScript
Save to your folder(s)

For those who refuse to upgrade.


Copy this code and paste it in your HTML
  1. // Tell IE9 to use its built-in console
  2. if (Function.prototype.bind && (typeof console === 'object' || typeof console === 'function') && typeof console.log == "object") {
  3. ["log","info","warn","error","assert","dir","clear","profile","profileEnd"]
  4. .forEach(function (method) {
  5. console[method] = this.call(console[method], console);
  6. }, Function.prototype.bind);
  7. }
  8.  
  9. // log() -- The complete, cross-browser (we don't judge!) console.log wrapper for his or her logging pleasure
  10. if (!window.log) {
  11. window.log = function () {
  12. log.history = log.history || []; // store logs to an array for reference
  13. log.history.push(arguments);
  14. // Modern browsers
  15. if (typeof console != 'undefined' && typeof console.log == 'function') {
  16.  
  17. // Opera 11
  18. if (window.opera) {
  19. var i = 0;
  20. while (i < arguments.length) {
  21. console.log("Item " + (i+1) + ": " + arguments[i]);
  22. i++;
  23. }
  24. }
  25.  
  26. // All other modern browsers
  27. else if ((Array.prototype.slice.call(arguments)).length == 1 && typeof Array.prototype.slice.call(arguments)[0] == 'string') {
  28. console.log( (Array.prototype.slice.call(arguments)).toString() );
  29. }
  30. else {
  31. console.log( Array.prototype.slice.call(arguments) );
  32. }
  33.  
  34. }
  35.  
  36. // IE8
  37. else if (!Function.prototype.bind && typeof console != 'undefined' && typeof console.log == 'object') {
  38. Function.prototype.call.call(console.log, console, Array.prototype.slice.call(arguments));
  39. }
  40.  
  41. // IE7 and lower, and other old browsers
  42. else {
  43. // Inject Firebug lite
  44. if (!document.getElementById('firebug-lite')) {
  45. // Include the script
  46. var script = document.createElement('script');
  47. script.type = "text/javascript";
  48. script.id = 'firebug-lite';
  49. // If you run the script locally, point to /path/to/firebug-lite/build/firebug-lite.js
  50. script.src = 'https://getfirebug.com/firebug-lite.js';
  51. // If you want to expand the console window by default, uncomment this line
  52. //document.getElementsByTagName('HTML')[0].setAttribute('debug','true');
  53. document.getElementsByTagName('HEAD')[0].appendChild(script);
  54. setTimeout(function () { log( Array.prototype.slice.call(arguments) ); }, 2000);
  55. }
  56. else {
  57. // FBL was included but it hasn't finished loading yet, so try again momentarily
  58. setTimeout(function () { log( Array.prototype.slice.call(arguments) ); }, 500);
  59. }
  60. }
  61. };
  62. }

URL: http://patik.com/blog/complete-cross-browser-console-log/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.