Code executor hook console.log solution

This demand is what I was doing code executor technical paper directly execute the code, I realized the problems encountered in the code actuators need to console.logoutput to a custom view. Two problems need to be solved to make this demand:

1. Be able to receive the content to be output by console.log, that is, get the parameter args of console.log(args); 

2. Does not affect the normal function of the original console.log;

The console is a global object that contains many methods, such as:

console.log();
console.error();

In fact, console.log is a function, and its usage is as follows:

// 可以输出多个对象
console.log(obj1 [, obj2, ..., objN]);
console.log(msg [, subst1, ..., substN]);

Since it is a function, just rewrite this function directly.

const reDefineConsoleLog = function (args) {
    const orgLog = console.log;
    const calls = [];
    console.log = (...args) => {
        // 把要打印的参数转换成字符串,显示到视图上
        let logs = [];
        for(let i = 0; i < args.length; i++) {
            let aLog = args[i];
            let logStr = JSON.stringify(aLog);
            if (!logStr) {
                if (typeof aLog === 'function') {
                    // function can not parse to json
                    logStr = aLog.constructor;
                }
            }
            logs.push(logStr);
        }
        let retLog = logs.join(' , ');
        orgLog(retLog);
    };
};

But the effect I want is to be able to convert objects such as strings, objects, arrays, and functions into strings, so that the content can be displayed on the UI. This implementation is different from the implementation in the browser.

When you print an object in the browser, it will be displayed as Object >, and the value of the object is actually obtained when you click it. The effect I want is actually to be directly displayed as a string. Finally, simply use the JSON.stringfy function to convert an object into a string, which meets my expectations. The effect is as follows:

This plan is not necessarily the most perfect, if you have a better plan, please leave a message and let me know. Come on, everybody!

Long press to follow

Su Yan "Front End Class"

Help 10W people get started and advanced to the front end

Guess you like

Origin blog.csdn.net/lefex/article/details/109712863