如何在Google Chrome浏览器JavaScript控制台中打印debugging消息?

如何在Google Chrome浏览器JavaScript控制台中打印debugging消息?

请注意,JavaScript控制台与JavaScript Debugger不同, 他们有不同的语法AFAIK,所以JavaScript Debugger中的打印命令在这里不起作用。 在JavaScript控制台中, print()会将参数发送给打印机。

从浏览器地址栏执行以下代码:

 javascript:console.log(2);

成功地将消息打印到Google Chrome中的“JavaScript控制台”。

改进Andru的想法,你可以编写一个脚本来创build控制台function,如果它们不存在的话:

 if (!window.console) console = {}; console.log = console.log || function(){}; console.warn = console.warn || function(){}; console.error = console.error || function(){}; console.info = console.info || function(){}; 

然后,使用以下任一项:

 console.log(...); console.error(...); console.info(...); console.warn(...); 

这些function将logging不同types的项目(可以根据日志,信息,错误或警告进行过滤),并且在控制台不可用时不会导致错误。 这些function将在Firebug和Chrome控制台中运行。

只需添加很多开发人员想念的一个很酷的function:

 console.log("this is %o, event is %o, host is %s", this, e, location.host); 

这是JavaScript对象的魔术般的转储点击和深层浏览内容。 只显示了%s

这也是很酷的:

 console.log("%s", new Error().stack); 

它给出了一个类似于Java的堆栈跟踪到new Error()调用点(包括文件和行号的path !)。

Chrome和Firefox都提供了%onew Error().stack

也用于Firefox的堆栈跟踪使用:

 console.trace(); 

正如https://developer.mozilla.org/en-US/docs/Web/API/console所说的。;

快乐的黑客!

更新 :有些库是由坏人编写的,它们为了自己的目的重新定义了console对象。 加载库之后要恢复原始的浏览器console ,请使用:

 delete console.log; delete console.warn; .... 

请参阅堆栈溢出问题还原console.log()

只是一个快速警告 – 如果你想在不删除所有console.log()的情况下在Internet Explorer中testing,你需要使用Firebug Lite,否则你会得到一些不是特别友好的错误。

(或者创build你自己的console.log(),它只是返回false。)

这是一个简短的脚本,检查控制台是否可用。 如果不是,则会尝试加载Firebug ,如果Firebug不可用,则会加载Firebug Lite。 现在你可以在任何浏览器中使用console.log 。 请享用!

 if (!window['console']) { // Enable console if (window['loadFirebugConsole']) { window.loadFirebugConsole(); } else { // No console, use Firebug Lite var firebugLite = function(F, i, r, e, b, u, g, L, I, T, E) { if (F.getElementById(b)) return; E = F[i+'NS']&&F.documentElement.namespaceURI; E = E ? F[i + 'NS'](E, 'script') : F[i]('script'); E[r]('id', b); E[r]('src', I + g + T); E[r](b, u); (F[e]('head')[0] || F[e]('body')[0]).appendChild(E); E = new Image; E[r]('src', I + L); }; firebugLite( document, 'createElement', 'setAttribute', 'getElementsByTagName', 'FirebugLite', '4', 'firebug-lite.js', 'releases/lite/latest/skin/xp/sprite.png', 'https://getfirebug.com/', '#startOpened'); } } else { // Console is already available, no action needed. } 

除了Delan Azabani的回答 ,我喜欢分享我的console.js ,我用于相同的目的。 我使用一组函数名称来创build一个noop控制台,在我看来,这是一个非常方便的方法,并且我照顾了具有console.logfunction但没有console.debug的Internet Explorer:

 // Create a noop console object if the browser doesn't provide one... if (!window.console){ window.console = {}; } // Internet Explorer has a console that has a 'log' function, but no 'debug'. To make console.debug work in Internet Explorer, // We just map the function (extend for info, etc. if needed) else { if (!window.console.debug && typeof window.console.log !== 'undefined') { window.console.debug = window.console.log; } } // ... and create all functions we expect the console to have (taken from Firebug). var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"]; for (var i = 0; i < names.length; ++i){ if(!window.console[names[i]]){ window.console[names[i]] = function() {}; } } 

或者使用这个function:

 function log(message){ if (typeof console == "object") { console.log(message); } } 

这是我的控制台包装类。 它给我的范围输出,以使生活更轻松。 请注意使用localConsole.debug.call()以便localConsole.debug在调用类的范围内运行,从而提供对toString方法的访问。

 localConsole = { info: function(caller, msg, args) { if ( window.console && window.console.info ) { var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg]; if (args) { params = params.concat(args); } console.info.apply(console, params); } }, debug: function(caller, msg, args) { if ( window.console && window.console.debug ) { var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg]; if (args) { params = params.concat(args); } console.debug.apply(console, params); } } }; someClass = { toString: function(){ return 'In scope of someClass'; }, someFunc: function() { myObj = { dr: 'zeus', cat: 'hat' }; localConsole.debug.call(this, 'someFunc', 'myObj: ', myObj); } }; someClass.someFunc(); 

这在Firebug中提供如下输出:

 In scope of someClass.someFunc(), myObj: Object { dr="zeus", more...} 

或Chrome:

 In scope of someClass.someFunc(), obj: Object cat: "hat" dr: "zeus" __proto__: Object 

我个人使用这个,类似于tarek11011的:

 // Use a less-common namespace than just 'log' function myLog(msg) { // Attempt to send a message to the console try { console.log(msg); } // Fail gracefully if it does not exist catch(e){} } 

主要的一点是,至less有一些好的想法,除了把console.log()直接放在你的JavaScript代码之外,至less有一些日志logging的做法,因为如果你忘了它,并且它在生产站点上,它可能会中断该页面的所有JavaScript代码。

你可以使用console.log()如果你在编程软件编辑器中有一个debugging过的代码,你会看到输出可能是我最好的编辑器(谷歌浏览器)。 只需按下F12并按下Console(控制台)选项卡。 你会看到结果。 快乐的编码。 🙂

()语句的开发人员遇到很多问题。 而且,我真的不喜欢debuggingInternet Explorer,尽pipeInternet Explorer 10和Visual Studio 2012等有了很大的改进。

所以,我已经覆盖了控制台对象本身…我已经添加了__localhost标志,只允许在本地主机上的控制台语句。 我还将控制台。()函数添加到Internet Explorer(显示alert())。

 // Console extensions... (function() { var __localhost = (document.location.host === "localhost"), __allow_examine = true; if (!console) { console = {}; } console.__log = console.log; console.log = function() { if (__localhost) { if (typeof console !== "undefined" && typeof console.__log === "function") { console.__log(arguments); } else { var i, msg = ""; for (i = 0; i < arguments.length; ++i) { msg += arguments[i] + "\r\n"; } alert(msg); } } }; console.__info = console.info; console.info = function() { if (__localhost) { if (typeof console !== "undefined" && typeof console.__info === "function") { console.__info(arguments); } else { var i, msg = ""; for (i = 0; i < arguments.length; ++i) { msg += arguments[i] + "\r\n"; } alert(msg); } } }; console.__warn = console.warn; console.warn = function() { if (__localhost) { if (typeof console !== "undefined" && typeof console.__warn === "function") { console.__warn(arguments); } else { var i, msg = ""; for (i = 0; i < arguments.length; ++i) { msg += arguments[i] + "\r\n"; } alert(msg); } } }; console.__error = console.error; console.error = function() { if (__localhost) { if (typeof console !== "undefined" && typeof console.__error === "function") { console.__error(arguments); } else { var i, msg = ""; for (i = 0; i < arguments.length; ++i) { msg += arguments[i] + "\r\n"; } alert(msg); } } }; console.__group = console.group; console.group = function() { if (__localhost) { if (typeof console !== "undefined" && typeof console.__group === "function") { console.__group(arguments); } else { var i, msg = ""; for (i = 0; i < arguments.length; ++i) { msg += arguments[i] + "\r\n"; } alert("group:\r\n" + msg + "{"); } } }; console.__groupEnd = console.groupEnd; console.groupEnd = function() { if (__localhost) { if (typeof console !== "undefined" && typeof console.__groupEnd === "function") { console.__groupEnd(arguments); } else { var i, msg = ""; for (i = 0; i < arguments.length; ++i) { msg += arguments[i] + "\r\n"; } alert(msg + "\r\n}"); } } }; /// <summary> /// Clever way to leave hundreds of debug output messages in the code, /// but not see _everything_ when you only want to see _some_ of the /// debugging messages. /// </summary> /// <remarks> /// To enable __examine_() statements for sections/groups of code, type the /// following in your browser's console: /// top.__examine_ABC = true; /// This will enable only the console.examine("ABC", ... ) statements /// in the code. /// </remarks> console.examine = function() { if (!__allow_examine) { return; } if (arguments.length > 0) { var obj = top["__examine_" + arguments[0]]; if (obj && obj === true) { console.log(arguments.splice(0, 1)); } } }; })(); 

使用示例:

  console.log("hello"); 

镀铬/火狐:

  prints hello in the console window. 

IE浏览器:

  displays an alert with 'hello'. 

对于那些密切关注代码的人,你会发现console.examine()函数。 我是在几年前创build的,所以我可以在产品的某些区域留下debugging代码,以帮助解决QA /客户问题。 例如,我将在一些发布的代码中留下以下行:

  function doSomething(arg1) { // ... console.examine("someLabel", arg1); // ... } 

然后从发布的产品中,在控制台(或以“javascript:”为前缀的地址栏)中input以下内容:

  top.__examine_someLabel = true; 

然后,我将看到所有logging的console.examine()语句。 这是一个很好的帮助很多次。

简单的Internet Explorer 7和以下的垫片 ,保留其他浏览器的行号:

 /* Console shim */ (function () { var f = function () {}; if (!window.console) { window.console = { log:f, info:f, warn:f, debug:f, error:f }; } }()); 
 console.debug(""); 

使用此方法在控制台中打印出明亮的蓝色文本。

在这里输入图像说明

进一步改进德兰和安德鲁的思想(这就是为什么这个答案是一个编辑版本); console.log可能存在,而其他function可能不会,所以有默认映射到console.log相同的function….

你可以编写一个脚本来创build控制台function,如果它们不存在的话:

 if (!window.console) console = {}; console.log = console.log || function(){}; console.warn = console.warn || console.log; // defaults to log console.error = console.error || console.log; // defaults to log console.info = console.info || console.log; // defaults to log 

然后,使用以下任一项:

 console.log(...); console.error(...); console.info(...); console.warn(...); 

这些function将logging不同types的项目(可以根据日志,信息,错误或警告进行过滤),并且在控制台不可用时不会导致错误。 这些function将在Firebug和Chrome控制台中运行。