如何在JavaScript中获取console.log内容作为字符串 [英] How to get the console.log content as string in JavaScript

查看:1380
本文介绍了如何在JavaScript中获取console.log内容作为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在纯JavaScript中获得console.log作为字符串。
我的输入是一个脚本,我不熟悉,我想收集console.log中的所有消息到一个字符串。

I'm trying to get the console.log as string in pure JavaScript. My input is a script, which I'm not familiar with, and I want to collect all the messages in the console.log into a string.

例如:

function doSomething(){
    console.log("start");
    console.log("end");
    var consoleLog = getConsoleLog();
    return consoleLog;
}

function getConsoleLog(){
    // How to implement this?
}

alert(doSomething());

JSFiddle链接< a>

JSFiddle link

请注意,我不需要提醒日志 - 这只是一个简单的测试功能的例子。

Note that I do not need to alert the log - this is just a simple example of testing the functionality. I'll have to do some operations on the log's content.

推荐答案

您可以覆盖 console.log 方法使用它之前:

You could overwrite console.log method before using it:

var logBackup = console.log;
var logMessages = [];

console.log = function() {
    logMessages.push.apply(logMessages, arguments);
    logBackup.apply(console, arguments);
};

使用 apply arguments 保留正确的 console.log 行为,即可以通过单个调用添加多个日志消息。

Using apply and arguments preserves the correct console.log behaviour, i.e. you can add multiple log messages with a single call.

它会将所有新 console.log 消息推送到 logMessages 数组。

It will push all new console.log messages to logMessages array.

这篇关于如何在JavaScript中获取console.log内容作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆