nakome
12/19/2015 - 1:36 AM

Console.js

(function() {
  // create pre,span and style  tag
  var _pre = document.createElement('pre'),
    _debug = document.createElement('span'),
    _closebtn = document.createElement('span'),
    _style = document.createElement('style');
  // append pre console
  _pre.id = 'console';
  document.body.appendChild(_pre);
  // append style
  _style.id = 'consoleStyle';
  _style.textContent = [
    '#console{',
      'box-sizing:border-box;',
      'position:fixed;',
      'left:0;',
      'bottom:0;',
      'margin:0;',
      'height:10em;',
      'width:100vw;',
      'padding:0;',
      'background:#F4F4F4;',
      'color: #226DD0;',
      'z-index:999999999;',
      'border-top:1px solid #E7E7E7;',
      'border-radius:0;',
      'overflow:hidden;',
      'word-break:break-all;',
      'word-wrap:break-word;',
      'transition:all 500ms linear',
    '}',
    '#debug {',
      'width:100%;',
      'margin-top:1em;',
      'padding:1em;',
      'height: 9em;',
      'overflow:auto;',
      'display:block;',
    '}',
    '#close{',
      'position:absolute;',
      'top: 0;',
      'right: 0.2em;',
      'background-color:#E8E8E8;',
      'border-left: 1px solid #D3D3D3;',
      'border-bottom: 1px solid #D5D4D4;',
      'color: #ED0C0C;',
      'padding:.2em;',
      'text-align:center;',
      'line-height:12px;',
      'font-size:20px;',
      'cursor:pointer;',
    '}'
    ].join('\n');
  document.getElementsByTagName('head')[0].appendChild(_style);
  // set id and html
  _closebtn.id = 'close';
  _closebtn.innerHTML = '&times';
  // hide console and append
  _pre.appendChild(_closebtn);
  // hide console if not error or console start
  _pre.style.bottom = '-10em';
  // close console
  _closebtn.onclick = function(e) {
      e.preventDefault();
      _pre.style.bottom = '-10em';
    };
    // debug id
  _debug.id = 'debug';
  // console function
  console.log = function(message) {
    // show console
    _pre.style.bottom = '0em';
    //if type obejct
    if (typeof message == 'object') {
      var result = [
        (JSON && JSON.stringify ? JSON.stringify(message) : message)
      ].join('\n');
      _debug.textContent += result;
      _pre.appendChild(_debug);
    } else {
      // normal
      _debug.textContent += message + '\n';
      _pre.appendChild(_debug);
    }
    _debug.scrollTop = _debug.scrollHeight + 50;
  };
  //clear console
  console.clear = function() {
    _debug.textContent = '';
  };
  // all in one
  console.error = console.info = console.trace = console.debug = console.log;
  // on error show
  window.onerror = function(err, file, line, column) {
    // show console
    _pre.style.bottom = '0em';
    _debug.textContent += [
      'Error: ' + err,
      'Line: ' + line + ' Column: ' + column
    ].join('\n');
    _debug.scrollTop = _debug.scrollHeight + 50;
    _pre.replaceChild(_debug);
  };
})();