2013-10-28 79 views

回答

5

如何捕獲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

1

您可以覆蓋的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); 
1

您可以使用eval()函數的字符串來評估JavaScript,然後打印輸出到一些格。這會給你一些REPL的功能。

const consoleElm = document.querySelector('#console'); 
 
const clearButton = document.querySelector('#clear'); 
 

 
clearButton.addEventListener('click', (event) => { 
 
\t consoleElm.innerHTML = ''; 
 
}); 
 

 
const consoleForm = document.querySelector('#console-form'); 
 
consoleForm.addEventListener('submit', (event) => { 
 
\t 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>