Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript console log in Magento

I have a custom phtml pages in Magento. As far I know Magento uses jQuery and prototype libraries.

For example, if I need external jQuery/jQueryUI, I need to use .noConflict()

But if I want to use

console.log('Hello world');

In Chrome 15 console I got no response, nothing. Also tried with Firebug.

Obviously there is some conflict with Magento JavaScript code. Is there any solution?

like image 283
enloz Avatar asked Nov 10 '11 13:11

enloz


2 Answers

So in light of not wanting to smear this site with profanity I will just say someone wasn't thinking in the magento team or somehow some crappy code got into live releases....

If your console.log() is not working on a Magento installation it is likely because of the following:

In magento/js/varien/js.js @ line ~636, Magento ver. 1.6.2.0

if (!("console" in window) || !("firebug" in console))
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}

This effectively prevents console.log() from working in any browser other than firefox with firebug.

To protect IE, surely, but I think this is the wrong way to get arround it, instead people should be aware of what they do with their logging and face the consequences when they don't.

To fix it just make sure you put delete window['console']; (javascript) before you try to do a console.log(), or if you don't mind modifying the core files, delete the code above.

Please note: remove the console fix for production, the delete doesn't work in IE6-8 and throws an error

like image 175
sg3s Avatar answered Oct 05 '22 11:10

sg3s


Adding this layout update in your app/design/frontend/default/default/layout/local.xml or your theme's app/design/frontend/default/default/layout/page.xml in the <default> handle is the cleanest, most direct way to add back the console object in all browsers on all pages.

<default>
    <reference name="content">
        <block type="core/text" name="fix.console" as="fix.console">
            <action method="setText">
                <text><![CDATA[<script type="text/javascript">
                    iframe                  = document.createElement('iframe');
                    iframe.style.display    = 'none';
                    document.getElementsByTagName('body')[0].appendChild(iframe);
                    window.console          = iframe.contentWindow.console;
                    console.firebug         = "faketrue";                   
                </script>]]></text>
            </action>
        </block>
    </reference>
</default>
like image 29
Anthony Avatar answered Oct 05 '22 12:10

Anthony