كيف يمكنني طباعة رسائل التصحيح في جوجل كروم جافا سكريبت وحدة ؟

StackOverflow https://stackoverflow.com/questions/217957

سؤال

كيف يمكنني طباعة رسائل التصحيح في جوجل كروم جافا سكريبت وحدة ؟

يرجى ملاحظة أن وحدة تحكم جافا سكريبت ليست نفس جافا سكريبت المصحح;لديهم جمل مختلفة AFAIK ، لذلك طباعة القيادة في جافا سكريبت المصحح لا تعمل هنا.في وحدة تحكم جافا سكريبت ، print() سوف ترسل المعلمة إلى الطابعة.

هل كانت مفيدة؟

المحلول

تنفيذ التعليمات البرمجية التالية من شريط عنوان المتصفح:

javascript: console.log(2);

بنجاح يطبع رسالة إلى "وحدة تحكم جافا سكريبت" في جوجل كروم.

نصائح أخرى

تحسين 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(...);

هذه الوظائف سيتم تسجيل أنواع مختلفة من العناصر (التي يمكن تصفيتها استنادا إلى سجل معلومات خطأ أو تحذير) ولن يسبب أخطاء عند وحدة التحكم غير متوفرة.هذه الوظائف سوف تعمل في الحرائق و كروم المفاتيح.

فقط إضافة ميزة رائعة فيها الكثير من المطورين ملكة جمال:

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

هذا هو السحرية %o تفريغ نقر العميقة للتصفح محتوى كائن جافا سكريبت. %s كان يظهر فقط وهو رقم قياسي.

أيضا هذا هو بارد جدا:

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

الذي يعطي جافا مثل تتبع المكدس إلى نقطة new Error() الاحتجاج (بما في ذلك المسار إلى الملف و رقم السطر!).

سواء %o و new Error().stack تتوفر في كروم و فايرفوكس!

أيضا تتبعات المكدس في فايرفوكس استخدام:

console.trace();

كما https://developer.mozilla.org/en-US/docs/Web/API/console يقول.

التقطيع سعيد!

التحديث:بعض المكتبات مكتوبة من قبل الناس سيئة والتي تعريف console كائن لأغراض خاصة بهم.لاستعادة الأصلي المتصفح console بعد تحميل المكتبة استخدام:

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

انظر تجاوز سعة مكدس السؤال استعادة وحدة التحكم.سجل().

سريعة فقط تحذير - إذا كنت ترغب في اختبار في Internet Explorer دون إزالة كل وحدة.سجل()'s, سوف تحتاج إلى استخدام الحرائق لايت أو سوف تحصل على بعض لا سيما ودية الأخطاء.

(أو إنشاء الخاصة بك وحدة التحكم.سجل() وهذا فقط بإرجاع false.)

هنا هو القصير النصي الذي يتحقق إذا كان وحدة التحكم المتاحة.إذا لم يكن ، فإنه يحاول تحميل الحرائق وإذا الحرائق لا تتوفر تحميل الحرائق لايت.الآن يمكنك استخدام 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();

وهذا يعطي الإخراج مثل ذلك في الحرائق:

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

أو كروم:

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() في شفرة جافا سكريبت, لأنه إذا كنت قد نسيت حول هذا الموضوع في موقع الإنتاج, يمكن كسر كل شفرة جافا سكريبت على تلك الصفحة.

هل يمكن استخدام console.log() إذا كان لديك تصحيحه رمز في البرمجة محرر البرامج لديك و سوف ترى الإخراج الأرجح أفضل محرر بالنسبة لي (جوجل كروم).فقط اضغط F12 ثم اضغط على التبويب وحدة التحكم.سوف ترى النتيجة.سعيد الترميز.:)

لقد كان الكثير من القضايا مع المطورين التحقق في وحدة التحكم.() البيانات.و أنا حقا لا أحب التصحيح Internet Explorer ، على الرغم من تحسينات رائعة من Internet Explorer 10 و Visual Studio 2012, ، وما إلى ذلك.

لقد تجاوز وحدة هدف في حد ذاته...لقد أضفت __localhost العلم أن يسمح فقط وحدة تحكم البيانات على المضيف المحلي.أود أيضا أن أضيف وحدة التحكم.() وظائف Internet Explorer (أن يعرض تنبيه() بدلا من ذلك).

// 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.

إنترنت إكسبلورر:

    displays an alert with 'hello'.

بالنسبة لأولئك الذين ننظر عن كثب في الكود, سوف تكتشف وحدة التحكم.دراسة() وظيفة.أنا خلقت هذا قبل سنوات حتى أستطيع أن أترك رمز التصحيح في بعض المناطق حول المنتج للمساعدة في استكشاف الأخطاء وإصلاحها سؤال وجواب/مشاكل العملاء.فعلى سبيل المثال, أنا أترك السطر التالي في بعض صدرت التعليمات البرمجية:

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

ثم من صدر المنتج, اكتب ما يلي في وحدة التحكم (أو شريط عنوان مسبوقة مع 'javascript:'):

    top.__examine_someLabel = true;

ثم سوف ترى جميع من تسجيل وحدة التحكم.دراسة() البيانات.انها كانت رائعة تساعد مرات عديدة على مدى.

بسيطة 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("");

باستخدام هذا الأسلوب يطبع النص في اللون الأزرق مشرق في وحدة التحكم.

enter image description here

زيادة تحسين على أفكار Delan و Andru (والذي هو السبب في هذا الجواب هو نسخة معدلة);وحدة التحكم.سجل من المحتمل أن توجد في حين أن وظائف أخرى قد لا حتى يكون الافتراضي الخريطة بنفس وظيفة وحدة التحكم.سجل....

يمكنك كتابة السيناريو الذي يخلق وظائف وحدة التحكم إذا لم تكن موجودة:

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(...);

هذه الوظائف سيتم تسجيل أنواع مختلفة من العناصر (التي يمكن تصفيتها استنادا إلى سجل معلومات خطأ أو تحذير) ولن يسبب أخطاء عند وحدة التحكم غير متوفرة.هذه الوظائف سوف تعمل في الحرائق و كروم المفاتيح.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top