I wrote this post because I was in an interview today and the interviewer asked me a question: how to get the text information of console.log and display it in the user interface. At that time, I felt a little confused. After the interview, I thought about it carefully because I didn’t have much time to think about it. It was not difficult to implement this feature.

The ES6 proxy intercepts all attributes of the console object, and proxies them to our customized console object for customized operations

First define a custom customConsoleHandler object. Insert all properties of the Console object into the custom customConsoleHandler object. This object is used to delegate all operations of console to this object

const customConsoleHandler = {} const originConsoleProperty = Object.getOwnPropertyNames(console); OriginConsoleProperty. ForEach (key = > {customConsole [key] = function mutator (values) {/ / we can go to the custom here some print operation}});Copy the code

Next, we need to intercept the Console object, and we need to delegate all user operations on the console object to our custom customConsoleHandler

let consoleProxy = new Proxy(console, {    
    get (target, key) {        
        target = customConsoleHandler.hasOwnProperty(key) ? customConsoleHandler : target;
        return Reflect.get(target, key);
 }})
Copy the code

This way we can do some custom operations by intercepting properties on the Console object and retrieving the parameters passed in

For example, to get the console.log parameter and print it to the screen, we could modify the first code as follows:

originConsoleProperty.forEach(key => { if (key === 'log') { customConsole[key] = function log (... args) { document.body.innerText = args.join(' '); }} else {customConsole[key] = function mutator (values) {Copy the code

By calling consoleproxy.log (‘ This is a test ‘), the body tag inserts a piece of text.

If there is a clerical error, welcome to correct, thank you.