I´m working on a big angular.js project.
Now, I´ve to profile some pages about the performance.
With the console.log of the project I´m looking for the performance problems.
I miss if console.log can output the current time (yes, I know in Chrome you can set up).
Is there a way (like in log4java) to format the output?
Thanks in advance,
Be careful, the console object should not be activated in production mainly because it can breaks the code for some users (for example IE8 or less users).
But if you want to test on a tool that you know, you can use the Web API interface which provides some useful method on this object:
https://developer.mozilla.org/en-US/docs/Web/API/Console
(This doc is from the Mozilla Developer Network (MDN) and therefore mainly applies to Firefox, but at the end of that page you can find links to the corresponding docs for the IE, Chrome and Safari DevTools as well as Firebug).
For example, you can use the time() method for your use case:
console.time("answer time");
// ... some other code
console.timeEnd("answer time");
Outputs something like this:
You could try something like this:
console = window.console ? console : {};
native_log = console.log;
window.console.log = function myConsole() {
// Cannot log if console.log is not present natively,
// so fail silently (in IE without debugger opened)
if (!native_log)
return;
var args = Array.prototype.slice.call(arguments);
args.unshift(new Date());
native_log.apply(console, args);
}
console.log('hello'); // Date 2014-12-02T14:14:50.138Z "hello"
Of course, you would not let the new Date() as is, but it gives you the idea.
Related
Is it possible to retrieve the browsers console.log with Selenium and Firefox 43? If so, how?
Here are my settings:
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
LoggingPreferences logs = new LoggingPreferences();
logs.enable(LogType.BROWSER, Level.ALL);
logs.enable(LogType.DRIVER, Level.ALL);
logs.enable(LogType.CLIENT, Level.ALL);
logs.enable(LogType.PERFORMANCE, Level.ALL);
logs.enable(LogType.PROFILER, Level.ALL);
logs.enable(LogType.SERVER, Level.ALL);
capabilities.setCapability(CapabilityType.LOGGING_PREFS, logs);
FirefoxBinary binary = new FirefoxBinary(new File(...));
FirefoxProfile profile = new FirefoxProfile();
WebDriver driver = new FirefoxDriver(binary, profile, capabilities);
//...doing things with the driver ...
driver.manage().logs().get(LogType.BROWSER) // already tried every LogType
The only output i get from this is something like:
1450878255029 addons.xpi DEBUG startup
...
Error in parsing value for 'display'. Declaration dropped.
But not the output which is written in the browsers javascript console log.
I already tried several FF profile settings like:
profile.setPreference("extensions.sdk.console.logLevel", "all");
profile.setPreference("webdriver.log.file",tempfile.getAbsolutePath());
profile.setPreference("webdriver.firefox.logfile", othertempfile.getAbsolutePath());
profile.setPreference("webdriver.log.driver", "ALL");
Nothing helped so far.
In Chrome this is working flawlessly.
Selenium version: 2.48.2
Firefox version: 43.0.2
I had the same issue. I only got all that log noise about css, security, network and what not, but not what was actually logged by the app through console.log. I am using the same version for webdriver and firefox you do. For other browsers this was not a problem.
I ended up extending my client code with custom log recording. Speaking in wire protocol terms:
use execute to put something like the following into the client
window.recordedLogs = [];
console.log = function (message) {
if (typeof message === 'object') {
message = JSON.stringify(message);
}
window.recordedLogs.push(message);
};
use execute to retrieve window.recordedLogs
Warning: the above code is very simplistic, it does not take care of multiple messages passed to the log method, nor does it handle other log methods like info, error, etc.
However it can be a good multi-browser-compliant alternative to the wire protocol log method.
I'm doing some javascript exercises on code wars. I want to see what's going wrong in my programs by printing to the console, but nothing except the test results appears in the output window. Does anyone know how to print to the console in code wars? I can't find anything in their documentation.
function areYouPlayingBanjo(name) {
// Implement me
var person = name.split('');
person[0].toLowerCase();
console.log(person[0]);
if(person[0] === 'r'){
return name + " plays banjo";
}
else{
return name + " does not play banjo";
}
}
This is not exactly an answer to the question, but more of an extended answer in order to document a chrome extension that can allow debugging in the console for codewars.
Install this chrome extension:
https://github.com/bojan88/Codewars-JavaScript-debugger
This allows you to use the debugger; statement to force the your code to run in the browser rather than the sandboxed environment on the codewars servers. Works great.
Caveat: I don't know if this is safe. Use at your own risk.
This worked for me:
Console.Out.WriteLine("Print stuff to output here.");
IE9 Bug - JavaScript only works after opening developer tools once.
Our site offers free pdf downloads to users, and it has a simple "enter password to download" function. However, it doesn't work at all in Internet Explorer.
You can see for yourself in this example.
The download pass is "makeuseof". In any other browser, it works fine. In IE, both buttons do nothing.
The most curious thing I've found is that if you open and close the developer toolbar with F12, it all suddenly starts to work.
We've tried compatibility mode and such, nothing makes a difference.
How do I make this work in Internet Explorer?
It sounds like you might have some debugging code in your javascript.
The experience you're describing is typical of code which contain console.log() or any of the other console functionality.
The console object is only activated when the Dev Toolbar is opened. Prior to that, calling the console object will result in it being reported as undefined. After the toolbar has been opened, the console will exist (even if the toolbar is subsequently closed), so your console calls will then work.
There are a few solutions to this:
The most obvious one is to go through your code removing references to console. You shouldn't be leaving stuff like that in production code anyway.
If you want to keep the console references, you could wrap them in an if() statement, or some other conditional which checks whether the console object exists before trying to call it.
HTML5 Boilerplate has a nice pre-made code for console problems fixing:
// Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
As #plus- pointed in comments, latest version is available on their GitHub page
Here's another possible reason besides the console.log issue (at least in IE11):
When the console is not open, IE does pretty aggressive caching, so make sure that any $.ajax calls or XMLHttpRequest calls have caching set to false.
For example:
$.ajax({cache: false, ...})
When the developer console is open, caching is less aggressive. Seems to be a bug (or maybe a feature?)
This solved my problem after I made a minor change to it. I added the following in my html page in order to fix the IE9 problem:
<script type="text/javascript">
// IE9 fix
if(!window.console) {
var console = {
log : function(){},
warn : function(){},
error : function(){},
time : function(){},
timeEnd : function(){}
}
}
</script>
Besides the 'console' usage issue mentioned in accepted answer and others,there is at least another reason why sometimes pages in Internet Explorer work only with the developer tools activated.
When Developer Tools is enabled, IE doesn't really uses its HTTP cache (at least by default in IE 11) like it does in normal mode.
It means if your site or page has a caching problem (if it caches more than it should for example - that was my case), you will not see that problem in F12 mode. So if the javascript does some cached AJAX requests, they may not work as expected in normal mode, and work fine in F12 mode.
I guess this could help, adding this before any tag of javascript:
try{
console
}catch(e){
console={}; console.log = function(){};
}
If you are using AngularJS version 1.X you could use the $log service instead of using console.log directly.
Simple service for logging. Default implementation safely writes the message into the browser's console (if present).
https://docs.angularjs.org/api/ng/service/$log
So if you have something similar to
angular.module('logExample', [])
.controller('LogController', ['$scope', function($scope) {
console.log('Hello World!');
}]);
you can replace it with
angular.module('logExample', [])
.controller('LogController', ['$scope', '$log', function($scope, $log) {
$log.log('Hello World!');
}]);
Angular 2+ does not have any built-in log service.
If you are using angular and ie 9, 10 or edge use :
myModule.config(['$httpProvider', function($httpProvider) {
//initialize get if not there
if (!$httpProvider.defaults.headers.get) {
$httpProvider.defaults.headers.get = {};
}
// Answer edited to include suggestions from comments
// because previous version of code introduced browser-related errors
//disable IE ajax request caching
$httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
// extra
$httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
$httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
}]);
To completely disable cache.
It happened in IE 11 for me. And I was calling the jquery .load function.
So I did it the old fashion way and put something in the url to disable cacheing.
$("#divToReplaceHtml").load('#Url.Action("Action", "Controller")/' + #Model.ID + "?nocache=" + new Date().getTime());
I got yet another alternative for the solutions offered by runeks and todotresde that also avoids the pitfalls discussed in the comments to Spudley's answer:
try {
console.log(message);
} catch (e) {
}
It's a bit scruffy but on the other hand it's concise and covers all the logging methods covered in runeks' answer and it has the huge advantage that you can open the console window of IE at any time and the logs come flowing in.
We ran into this problem on IE 11 on Windows 7 and Windows 10. We discovered what exactly the problem was by turning on debugging capabilities for IE (IE > Internet Options > Advanced tab > Browsing > Uncheck Disable script debugging (Internet Explorer)). This feature is typically checked on within our environment by the domain admins.
The problem was because we were using the console.debug(...) method within our JavaScript code. The assumption made by the developer (me) was I did not want anything written if the client Developer Tools console was not explicitly open. While Chrome and Firefox seemed to agree with this strategy, IE 11 did not like it one bit. By changing all the console.debug(...) statements to console.log(...) statements, we were able to continue to log additional information in the client console and view it when it was open, but otherwise keep it hidden from the typical user.
I put the resolution and fix for my issue . Looks like AJAX request that I put inside my JavaScript was not processing because my page was having some cache problem. if your site or page has a caching problem you will not see that problem in developers/F12 mode. my cached JavaScript AJAX requests it may not work as expected and cause the execution to break which F12 has no problem at all.
So just added new parameter to make cache false.
$.ajax({
cache: false,
});
Looks like IE specifically needs this to be false so that the AJAX and javascript activity run well.
IE9 Bug - JavaScript only works after opening developer tools once.
Our site offers free pdf downloads to users, and it has a simple "enter password to download" function. However, it doesn't work at all in Internet Explorer.
You can see for yourself in this example.
The download pass is "makeuseof". In any other browser, it works fine. In IE, both buttons do nothing.
The most curious thing I've found is that if you open and close the developer toolbar with F12, it all suddenly starts to work.
We've tried compatibility mode and such, nothing makes a difference.
How do I make this work in Internet Explorer?
It sounds like you might have some debugging code in your javascript.
The experience you're describing is typical of code which contain console.log() or any of the other console functionality.
The console object is only activated when the Dev Toolbar is opened. Prior to that, calling the console object will result in it being reported as undefined. After the toolbar has been opened, the console will exist (even if the toolbar is subsequently closed), so your console calls will then work.
There are a few solutions to this:
The most obvious one is to go through your code removing references to console. You shouldn't be leaving stuff like that in production code anyway.
If you want to keep the console references, you could wrap them in an if() statement, or some other conditional which checks whether the console object exists before trying to call it.
HTML5 Boilerplate has a nice pre-made code for console problems fixing:
// Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
As #plus- pointed in comments, latest version is available on their GitHub page
Here's another possible reason besides the console.log issue (at least in IE11):
When the console is not open, IE does pretty aggressive caching, so make sure that any $.ajax calls or XMLHttpRequest calls have caching set to false.
For example:
$.ajax({cache: false, ...})
When the developer console is open, caching is less aggressive. Seems to be a bug (or maybe a feature?)
This solved my problem after I made a minor change to it. I added the following in my html page in order to fix the IE9 problem:
<script type="text/javascript">
// IE9 fix
if(!window.console) {
var console = {
log : function(){},
warn : function(){},
error : function(){},
time : function(){},
timeEnd : function(){}
}
}
</script>
Besides the 'console' usage issue mentioned in accepted answer and others,there is at least another reason why sometimes pages in Internet Explorer work only with the developer tools activated.
When Developer Tools is enabled, IE doesn't really uses its HTTP cache (at least by default in IE 11) like it does in normal mode.
It means if your site or page has a caching problem (if it caches more than it should for example - that was my case), you will not see that problem in F12 mode. So if the javascript does some cached AJAX requests, they may not work as expected in normal mode, and work fine in F12 mode.
I guess this could help, adding this before any tag of javascript:
try{
console
}catch(e){
console={}; console.log = function(){};
}
If you are using AngularJS version 1.X you could use the $log service instead of using console.log directly.
Simple service for logging. Default implementation safely writes the message into the browser's console (if present).
https://docs.angularjs.org/api/ng/service/$log
So if you have something similar to
angular.module('logExample', [])
.controller('LogController', ['$scope', function($scope) {
console.log('Hello World!');
}]);
you can replace it with
angular.module('logExample', [])
.controller('LogController', ['$scope', '$log', function($scope, $log) {
$log.log('Hello World!');
}]);
Angular 2+ does not have any built-in log service.
If you are using angular and ie 9, 10 or edge use :
myModule.config(['$httpProvider', function($httpProvider) {
//initialize get if not there
if (!$httpProvider.defaults.headers.get) {
$httpProvider.defaults.headers.get = {};
}
// Answer edited to include suggestions from comments
// because previous version of code introduced browser-related errors
//disable IE ajax request caching
$httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
// extra
$httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
$httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
}]);
To completely disable cache.
It happened in IE 11 for me. And I was calling the jquery .load function.
So I did it the old fashion way and put something in the url to disable cacheing.
$("#divToReplaceHtml").load('#Url.Action("Action", "Controller")/' + #Model.ID + "?nocache=" + new Date().getTime());
I got yet another alternative for the solutions offered by runeks and todotresde that also avoids the pitfalls discussed in the comments to Spudley's answer:
try {
console.log(message);
} catch (e) {
}
It's a bit scruffy but on the other hand it's concise and covers all the logging methods covered in runeks' answer and it has the huge advantage that you can open the console window of IE at any time and the logs come flowing in.
We ran into this problem on IE 11 on Windows 7 and Windows 10. We discovered what exactly the problem was by turning on debugging capabilities for IE (IE > Internet Options > Advanced tab > Browsing > Uncheck Disable script debugging (Internet Explorer)). This feature is typically checked on within our environment by the domain admins.
The problem was because we were using the console.debug(...) method within our JavaScript code. The assumption made by the developer (me) was I did not want anything written if the client Developer Tools console was not explicitly open. While Chrome and Firefox seemed to agree with this strategy, IE 11 did not like it one bit. By changing all the console.debug(...) statements to console.log(...) statements, we were able to continue to log additional information in the client console and view it when it was open, but otherwise keep it hidden from the typical user.
I put the resolution and fix for my issue . Looks like AJAX request that I put inside my JavaScript was not processing because my page was having some cache problem. if your site or page has a caching problem you will not see that problem in developers/F12 mode. my cached JavaScript AJAX requests it may not work as expected and cause the execution to break which F12 has no problem at all.
So just added new parameter to make cache false.
$.ajax({
cache: false,
});
Looks like IE specifically needs this to be false so that the AJAX and javascript activity run well.
I am trying to browse a website, however, it only works under Windows and Mac because they use the navigator.platform from JavaScript to find out the architecture I am running on. Of course, they also use the browser's user agent, but that was easy to spoof.
Here is the .js in question: http://pastebin.com/f56fd608d. The code responsible for browser detection is at the top. Is there any way of changing the .js file before the site runs, or something similar, so I can eliminate the check?
Using the JavaScript console yields:
>navigator.platform
Linux i686
Evidently I changed the browser's user agent, but navigator.platform does not seem to take it's value from the user agent.
Maybe someone knows how to change the value returned by navigator.platform, because I hate running Windows under VirtualBox to use this site.
EDIT:
This could be of interest because Linux users might be artificially denied access to websites, and can do nothing about it.
var fakePlatformGetter = function () {
return "your fake platform";
};
if (Object.defineProperty) {
Object.defineProperty(navigator, "platform", {
get: fakePlatformGetter
});
Object.defineProperty(Navigator.prototype, "platform", {
get: fakePlatformGetter
});
} else if (Object.prototype.__defineGetter__) {
navigator.__defineGetter__("platform", fakePlatformGetter);
Navigator.prototype.__defineGetter__("platform", fakePlatformGetter);
}
Since you can't directly set navigator.platform, you will have to be sneaky - create an object that behaves like navigator, replace its platform, then set navigator to it.
var fake_navigator = {};
for (var i in navigator) {
fake_navigator[i] = navigator[i];
}
fake_navigator.platform = 'MyOS';
navigator = fake_navigator;
If you execute this code before the document loads (using GreaseMonkey, an addon or a Chrome extension), then the page will see navigator.platform as "MyOS".
Note: tested only in Chrome.
Provided that the browser you're using supports Object.defineProperty() (it likely does), a more modern way of achieving the same goal is as follows:
Object.defineProperty(navigator, 'platform', {
value: 'my custom value',
configurable: true // necessary to change value more than once
});
This allows you to set it to any custom value you want, and it also allows you to change it as many times as you want without needing to reload the page.
For a Mozilla-based browser, GreaseSpot / Code Snippets # Hijacking browser properties demonstrates how it may be done. This code may be injected from a GreaseMonkey script.
about:config - > general.platform.override
Attempting to change this property (at any time) in Firefox yields:
Error: setting a property that has only a getter
Source File: index.html
Line: 1
So I think you will have a hard time.
I'd try to contact the author about obtaining a fix.