Showing posts with label Debugging. Show all posts
Showing posts with label Debugging. Show all posts

Monday, April 29, 2019

Make Your Console Statements Stand Out

Using the Chrome DevTools to debug your JavaScript code is great. Breakpoints are a great way to analyze what is going on with your code. But sometimes you just need an old-fashioned console.log. But if you have an app that is already chatty in development mode with a lot of console messages, there is a way to make your console statement stand out. You may not know that you can format your console statements with CSS. For example:
console.log('%cExample', 'background: #a00; color: #fff; font-weight: bold; font-size: 110%');
will look like this in your console:

Example

A better way to do it, though, is to use a JavaScript template literal. For example:
let xyz = 123;
console.log('%c%s', 'background: #a00; color: #fff; font-weight: bold; font-size: 110%', 
  `The value of xyz is ${xyz}`);
Will produce:

The value of xyz is 123

Now to make it even easier, we can create a VS Code snippet:
"color-console": {
 "prefix": "color-console",
 "body": [
  "console.log('%c%s', 'background: #a00; color: #fff; font-weight: bold; font-size: 110%', `$1`);"
 ],
 "description": "Color coded console message"
},
And then voilĂ 

Tuesday, April 24, 2018

Stopping a page redirect to look at JavaScript console

I am currently assisting another developer troubleshoot an issue he's having. In the code, there is a JavaScript function call tied to the onclick event of the HTML link. Because the JavaScript code is failing, the page is redirecting before I have a change to look at the console log to see what the error is. One solution is to use a breakpoint in the code and that's what I'll ultimately do. But I found this great hack.

window.addEventListener("beforeunload", function() { debugger; }, false)

By running this code in the console first, it will pause execution and allow me to see the error in the console.
 
Blogger Templates