Colors in JavaScript console

前端 未结 27 2637
说谎
说谎 2020-11-22 11:42

Can Chrome\'s built-in JavaScript console display colors?

I want errors in red, warnings in orange and console.log\'s in green. Is that possible?

27条回答
  •  忘掉有多难
    2020-11-22 12:07

    Try this:

    var funcNames = ["log", "warn", "error"];
    var colors = ['color:green', 'color:orange', 'color:red'];
    
    for (var i = 0; i < funcNames.length; i++) {
        let funcName = funcNames[i];
        let color = colors[i];
        let oldFunc = console[funcName];
        console[funcName] = function () {
            var args = Array.prototype.slice.call(arguments);
            if (args.length) args = ['%c' + args[0]].concat(color, args.slice(1));
            oldFunc.apply(null, args);
        };
    }
    

    now they all are as you wanted:

    console.log("Log is green.");
    console.warn("Warn is orange.");
    console.error("Error is red.");
    

    note: formatting like console.log("The number = %d", 123); is not broken.

提交回复
热议问题