【问题标题】:Embed JS Console within website在网站内嵌入 JS 控制台
【发布时间】:2013-11-07 07:42:45
【问题描述】:

我想在网站中嵌入一个 JS-Console 以进行扩展调试。有没有可用的库或钩子?如何捕获 console.log 消息?

【问题讨论】:

    标签: html console javascript


    【解决方案1】:

    如何捕获 console.log 消息?

    您可以对真正的console.log 方法进行猴子修补,然后对输入进行任何您喜欢的操作:

    var realConsoleLog = console.log;
    console.log = function () {
        var message = [].join.call(arguments, " ");
        // Display the message somewhere... (jQuery example)
        $(".output").text(message);
        realConsoleLog.apply(console, arguments);
    };
    

    这是working example。它在.output 元素中记录对console.log 的调用,以及像往常一样在控制台中。

    【讨论】:

      【解决方案2】:

      你可以覆盖console.log

      <div id="console"></div>
      

      脚本:

      if (window.console) console = { 
          log: function(){
              var output='',
                  console=document.getElementById('console');
              for (var i=0;i<arguments.length;i++) {
                  output+=arguments[i]+' ';
              }
              console.innerText+=output+"\n";
          }
      };
      
      //test
      var test=12345;
      console.log('test', 'xyz', test);
      

      【讨论】:

        【解决方案3】:

        您可以使用eval() 函数评估字符串中的javascript,然后将该输出打印到某个div。这会给你一些 REPL 的能力。

        const consoleElm = document.querySelector('#console');
        const clearButton = document.querySelector('#clear');
        
        clearButton.addEventListener('click', (event) => {
        	consoleElm.innerHTML = '';
        });
        
        const consoleForm = document.querySelector('#console-form');
        consoleForm.addEventListener('submit', (event) => {
        	event.preventDefault();
          const command = event.target.querySelector('#command').value;
          const value = eval(command);
          consoleElm.innerHTML += (value === undefined ? 'undefined' : value) + '\n';
        });
        <div>
          <form id="console-form">
            <input type="text" id="command">
            <input type="submit" value="Run Command">
            <button id="clear" type="button">Clear</button>
          </form>
          <hr>
          <pre id="console"></pre>
        </div>

        【讨论】:

          猜你喜欢
          • 2013-04-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-11-11
          • 2021-02-26
          • 1970-01-01
          • 1970-01-01
          • 2019-10-09
          相关资源
          最近更新 更多