Google Chrome JavaScriptコンソールでデバッグメッセージを印刷するにはどうすればよいですか?
-
03-07-2019 - |
質問
Google Chrome JavaScriptコンソールでデバッグメッセージを印刷するにはどうすればよいですか
JavaScriptコンソールはJavaScriptデバッガーと同じではないことに注意してください。異なる構文があるため、JavaScriptデバッガーの print コマンドはここでは機能しません。 JavaScriptコンソールでは、 print()
がパラメーターをプリンターに送信します。
解決
ブラウザのアドレスバーから次のコードを実行します。
javascript: console.log(2);
「JavaScriptコンソール」にメッセージを正常に出力します; Google Chromeで。
他のヒント
Andruのアイデアを改善して、コンソール機能が存在しない場合にコンソール機能を作成するスクリプトを書くことができます:
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(...);
これらの関数はさまざまな種類の項目をログに記録し(ログ、情報、エラー、または警告に基づいてフィルタリングできます)、コンソールが利用できない場合でもエラーを引き起こしません。これらの機能は、FirebugおよびChromeコンソールで動作します。
多くの開発者が見落としているクールな機能を追加するだけです:
console.log("this is %o, event is %o, host is %s", this, e, location.host);
これはJavaScriptオブジェクトの魔法の%o
ダンプクリック可能かつ詳細な閲覧可能コンテンツです。 %s
はレコードについてのみ表示されました。
これもクールです:
console.log("%s", new Error().stack);
これは、Javaのようなスタックトレースを new Error()
呼び出しのポイントに提供します(ファイルおよび行番号へのパスを含む!)。
%o
と new Error()。stack
の両方がChromeとFirefoxで利用可能です!
Firefoxのスタックトレースにも使用:
console.trace();
As https://developer.mozilla.org/en-US / docs / Web / API / console に記載されています。
ハッピーハッキング!
更新:一部のライブラリは、 console
オブジェクトを独自の目的で再定義する悪意のある人々によって作成されています。ライブラリのロード後に元のブラウザの console
を復元するには、次を使用します。
delete console.log;
delete console.warn;
....
スタックオーバーフローの質問 console.log()の復元 を参照してください。
ちょっとした警告-すべてのconsole.log()を削除せずにInternet  Explorerでテストする場合は、 Firebug Lite を使用しないと、特にわかりにくいエラーが表示されます。
(またはfalseを返す独自のconsole.log()を作成します。)
これは、コンソールが使用可能かどうかを確認する短いスクリプトです。そうでない場合、 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
を共有したい私は同じ目的で使用しています。関数名の配列を使用してnoopコンソールを作成します。これは非常に便利な方法であると思いますが、Internet  Explorerには console.log
関数がありますが、いいえ console.debug
:
// 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 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){}
}
主なポイントは、少なくとも console.log()
をJavaScriptコードに貼り付ける以外に、少なくともロギングの練習をすることをお勧めすることです。実稼働サイトにある場合、そのページのJavaScriptコードがすべて破損する可能性があります。
console.log()
は、使用しているプログラミングソフトウェアエディターにデバッグされたコードがある場合に使用でき、出力はおそらく私にとって最適なエディター(Google Chrome)になります。 F12 を押して、[コンソール]タブを押します。結果が表示されます。ハッピーコーディング。 :)
私は、開発者がconsole。()ステートメントをチェックインする際に多くの問題を抱えています。そして、 Internet&nbsp; Explorer10 および Visual&nbsp; Studio&nbsp; 2012 など
それで、コンソールオブジェクト自体をオーバーライドしました... localhostでコンソールステートメントのみを許可する__localhostフラグを追加しました。また、console。()関数をInternet&nbsp; 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");
Chrome / Firefox:
prints hello in the console window.
Internet Explorer:
displays an alert with 'hello'.
コードをよく見ると、console.examine()関数が見つかります。数年前に作成したため、 QA /顧客の問題。たとえば、リリースされたコードに次の行を残します:
function doSomething(arg1) {
// ...
console.examine("someLabel", arg1);
// ...
}
そしてリリースされた製品から、コンソールに次のように入力します(または「javascript:」というプレフィックスが付いたアドレスバー):
top.__examine_someLabel = true;
その後、記録されたconsole.examine()ステートメントがすべて表示されます。これは何度も素晴らしい助けになりました。
シンプルなインターネット&nbsp; Explorer&nbsp; 7 以下 shim は、他のブラウザーの行番号を保持します:
/* Console shim */
(function () {
var f = function () {};
if (!window.console) {
window.console = {
log:f, info:f, warn:f, debug:f, error:f
};
}
}());
DelanとAndruのアイデアをさらに改善する(これが、この回答が編集されたバージョンである理由です)。 console.logは存在する可能性がありますが、他の機能は存在しない可能性があるため、console.log ....と同じ機能へのデフォルトマップを用意してください。
コンソール関数が存在しない場合は作成するスクリプトを作成できます:
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(...);
これらの関数はさまざまな種類の項目をログに記録し(ログ、情報、エラー、または警告に基づいてフィルタリングできます)、コンソールが利用できない場合でもエラーを引き起こしません。これらの機能は、FirebugおよびChromeコンソールで動作します。