Environment switcher bookmarklet

Development tasks often require for the developer to compare how a given page looks on different environments. Even though the manual task of editing the URL is not a hard task, it's way better to have a quick way to do it. The mere act of stopping to think on how to adjust the URL affects the focus your mind has on the real dev task at hand. Let's see the bookmarklet I wrote to solve that.

Looking around the web, it's clear that the usual bookmarklets are quite simple; they just allow switching in a fixed way between dev and prod. But what if there are more environments? (e.g. QA). For that use case, this new bookmarklet works quite nicely.

The code shown here is the template source, remember to adjust it according to your needs (see the comments):

var curLoc = new String(window.location.href);
var newLoc = '';

// Prefixes for each environment
var prodPrefix = 'www.acme.com/subdir';
var qaPrefix = 'www.qa.acme.com/subdir';
var devPrefix = 'localhost:8000';

// env object relating each env key with its default config
var envs = {
  'prod': {
    'curPrefix': prodPrefix,
    'destPrefix': 'dev' //devPrefix
  },
  'qa': {
    'curPrefix': qaPrefix,
    'destPrefix': 'dev' //devPrefix
  },
  'dev': {
    'curPrefix': devPrefix,
    'destPrefix': 'prod' //prodPrefix
  }
};
// Shortcuts: key is shortcut, value is key on envs object.
var shortcuts = {
  'p': 'prod',
  'q': 'qa',
  'd': 'dev'
};
// Determine current env and default destination for redirection
for (env in envs) {
  if (curLoc.indexOf(envs[env].curPrefix) > -1) {
    var curPrefix = envs[env].curPrefix;
    var defaultDestPrefix = envs[env].destPrefix;
  }
}
// Allow user to override the default
var destPrefix = prompt('Enter destination environment (prod, qa, dev)', defaultDestPrefix);
// Try to expand shortcut
if (shortcuts.hasOwnProperty(destPrefix)) {
  destPrefix = shortcuts[destPrefix];
}
// Generate newLoc
if (envs.hasOwnProperty(destPrefix)) {
  newLoc = curLoc.replace(curPrefix, envs[destPrefix].curPrefix);
}
// Browse to newLoc
if (newLoc !== curLoc && newLoc.length > 0) {
  window.location = newLoc;
}

To get a working bookmarklet, I use this tool; instructions on how to get the bookmarklet in your bookmarks bar is given right there.

Code is also available as a gist.

Hope you find it useful!