在 HTML 页面中显示浏览器控制台

编辑:我找到了 Stack Overflow 使用的代码:https ://github.com/gh-canon/stack-snippet-console


我找到了一堆答案,这些答案显示了如何将控制台输出到网页,但我正在努力做到这一点,以便消息也记录到控制台。具有讽刺意味的是,如果您在 Stack Overflow 上运行代码片段,它们会按照我的意愿行事。


// This causes a stack overflow

var native = window;

native.console = {

    log: function(message){

        $('ul.messages').append('<li>Log: ' + message + '</li>');

        console.log(message);

    },

    error: function(message){

        $('ul.messages').append('<li>Error: ' + message + '</li>');

        console.error(message);

    },

    warn: function(message){

        $('ul.messages').append('<li>Warn: ' + message + '</li>');

        console.warn(message);

    }

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="messages"></ul>


富国沪深
浏览 224回答 3
3回答

喵喔喔

我认为你只需要缓存原始console方法并从缓存中调用它们——你现在拥有它的方式调用你的 stubbed log,这会导致无限递归(从而导致堆栈溢出):$(document).ready(function(){&nbsp; &nbsp; console.log('You should know...');&nbsp; &nbsp; console.error('Something went wrong...');&nbsp; &nbsp; console.warn('Look out for this...');})// This should workvar native = window;var originalConsole = native.console;native.console = {&nbsp; &nbsp; log: function(message){&nbsp; &nbsp; &nbsp; &nbsp; $('ul.messages').append('<li>Log: ' + message + '</li>');&nbsp; &nbsp; &nbsp; &nbsp; originalConsole.log(message);&nbsp; &nbsp; },&nbsp; &nbsp; error: function(message){&nbsp; &nbsp; &nbsp; &nbsp; $('ul.messages').append('<li>Error: ' + message + '</li>');&nbsp; &nbsp; &nbsp; &nbsp; originalConsole.error(message);&nbsp; &nbsp; },&nbsp; &nbsp; warn: function(message){&nbsp; &nbsp; &nbsp; &nbsp; $('ul.messages').append('<li>Warn: ' + message + '</li>');&nbsp; &nbsp; &nbsp; &nbsp; originalConsole.warn(message);&nbsp; &nbsp; }}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><h3>messages</h3><ul class="messages"></ul>

拉丁的传说

您可以创建一个包装函数,该函数接受一个函数并输出您修改后的函数。const wrapper = (fn, name) => {&nbsp; return function(msg) {&nbsp; &nbsp; $('ul.messages').append(`<li>${name}: ${msg}</li>`);&nbsp; &nbsp; fn(msg);&nbsp; };}$(document).ready(() => {&nbsp; window.console.log = wrapper(console.log, "Log");&nbsp; window.console.warn = wrapper(console.warn, "Warn");&nbsp; window.console.error = wrapper(console.error, "Error");});

慕侠2389804

我不建议您修改原始功能,您可以创建一个新功能,并且可以在控制台和您的节点上显示消息。Blow 是纯JavaScript 代码。示例 1function decorator(wrap, func) {&nbsp; return (...para) => {&nbsp; &nbsp; func(para)&nbsp; &nbsp; return wrap(para)&nbsp; }}const mylog = decorator(window.console.log, (...para)=>{&nbsp; const ul = document.querySelector(`ul[class=msg]`)&nbsp; const range = document.createRange()&nbsp; const frag = range.createContextualFragment(`<li>${para}</li>`)&nbsp; ul.append(frag)})mylog("Hello world!")<h3>messages</h3><ul class="msg"></ul>示例 2window.onload = () => {&nbsp; &nbsp; const decoratorFunc = (methodName, msg) => {&nbsp; &nbsp; &nbsp; const symbol = methodName === "info" ? "🐬" :&nbsp; &nbsp; &nbsp; &nbsp; methodName === "error" ? "❌" :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; methodName === "warn" ? "⚠" : ""&nbsp; &nbsp; &nbsp; const ul = document.querySelector(`ul[class=msg]`)&nbsp; &nbsp; &nbsp; const range = document.createRange()&nbsp; &nbsp; &nbsp; const frag = range.createContextualFragment(`<li>${symbol} ${msg}</li>`)&nbsp; &nbsp; &nbsp; ul.append(frag)&nbsp; &nbsp; }&nbsp; &nbsp; const myConsole = new MethodDecorator(window.console, decoratorFunc)&nbsp; &nbsp; myConsole.Apply(["log", "info", "error", "warn", // those will run {decoratorFunc + ``window.console.xxx``}&nbsp; &nbsp; &nbsp; "others" // 👈 I created, it doesn't belong method of window.console so it only run ``decoratorFunc``&nbsp; &nbsp; ])&nbsp; &nbsp; myConsole.log("log test")&nbsp; &nbsp; myConsole.info("info test")&nbsp; &nbsp; console.info("not influenced") // not influenced&nbsp; &nbsp; myConsole.error("error test")&nbsp; &nbsp; myConsole.warn("warn test")&nbsp; &nbsp; myConsole.others("others test")&nbsp; &nbsp; myConsole.Reset()&nbsp; &nbsp; // myConsole.warn("warn test") // error}class MethodDecorator {&nbsp; constructor(obj, func) {&nbsp; &nbsp; this.obj = obj&nbsp; &nbsp; this.func = func&nbsp; }&nbsp; Apply(nameArray) {&nbsp; &nbsp; const orgMethodNameArray = Object.getOwnPropertyNames(this.obj)&nbsp; &nbsp; for (const methodName of nameArray) {&nbsp; &nbsp; &nbsp; const orgMethodName = orgMethodNameArray.find(e => e === methodName) // if not found return undefined&nbsp; &nbsp; &nbsp; const prop = {}&nbsp; &nbsp; &nbsp; prop[methodName] = {&nbsp; &nbsp; &nbsp; &nbsp; "configurable": true,&nbsp; &nbsp; &nbsp; &nbsp; "value": (...args) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.func(methodName, args) // decorator function&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (orgMethodName) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.obj[orgMethodName](args) // for example, console.log(args)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; Object.defineProperties(this, prop)&nbsp; &nbsp; }&nbsp; }&nbsp; Reset() {&nbsp; &nbsp; const extraMethodNameArray = Object.getOwnPropertyNames(this).filter(name => name !== "obj" || name !== "func")&nbsp; &nbsp; for (const extraMethodName of extraMethodNameArray) {&nbsp; &nbsp; &nbsp; const prop = {}&nbsp; &nbsp; &nbsp; prop[extraMethodName] = {&nbsp; &nbsp; &nbsp; &nbsp; value: undefined&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; Object.defineProperties(this, prop)&nbsp; &nbsp; }&nbsp; }}<h3>messages</h3><ul class="msg"></ul>👆&nbsp;Run code snippet的控制台会屏蔽部分内容。单击运行代码片段后单击整页以查看所有内容。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript