I often find myself wanting to do something in the web browser when I'm developing a site, but not when it is in production. For example, I don't want our development team polluting Google Analytics data, and I only want to log errors while the site is in local development or in our staging environment but not in production.

While it is possible to set up an environment conditional on the server, I think it makes a lot of sense to do this on the client with JavaScript.

We'll need 4 functions:

  1. Check for URL parameters.
  2. Check for a cookie.
  3. Set a cookie.
  4. Set devmode.

We'll be able to go into devmode by using a URL query string, or by using the JavaScript console in the browser. Our devmode setting will persist between browser sessions by setting a cookie on the domain.

Checkout the sample web site code:

The action happens at the bottom of the JavaScript where we call PAGE.devmode() which accepts a boolean that will set the devmode if true. Notice how we check for the 'devmode' cookie or 'devmode' URL parameter in the call to PAGE.devmode().

This is a screenshot of my JavaScript console in Chrome as I was manually switching modes:

Browser console showing devmode.
Chrome JavaScript console showing switching between modes.

You could easily set a conditional for your Analytics and then ask everyone on your team to access the site once with the URL parameter '?devemode=1' like 'http://www.example.com/?devmode=1'. This will cause our JavaScript to put the page into devmode and set a cookie so the site always goes into devmode when accessed by those users. If anyone on the team needs to access the site in production mode, just tell them to clear their cookies and the devmode persistance will be removed.

Additionally you could set the mode from the server by injecting inline JavaScript into the page from your templating engine.

Anyway, I've found this way of controlling browser mode so useful that I almost always include it in all my projects.