How to get the console.log content as string in JavaScript(如何在 JavaScript 中将 console.log 内容作为字符串获取)
问题描述
我正在尝试将 console.log 作为纯 JavaScript 中的字符串.我的输入是一个脚本,我不熟悉,我想把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 链接
请注意,我不需要提醒日志 - 这只是测试功能的一个简单示例.我得对日志的内容做一些操作.
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 内容作为字符串获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 JavaScript 中将 console.log 内容作为字符串获


- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01