Brian Smith Brian Smith - 1 year ago 128
Javascript Question

Writing a chrome extension to change base url with saved presets

I work with SAAS offering (ServiceNow) with 5 different environments. I find myself frequently switching environments where the only difference is the base URL.

I've never done any plug-in work so I'm not sure if this is feasible but I'd like to set my a few base URL presets and be able to take the current URL and just swap the base with a click of a button.

Xan Xan
Answer Source

It's totally possible.

The pointer in general direction is the chrome.tabs API: you'll be able to manipulate a tab's URL with it.

UI-wise, you get a button on the toolbar called a Browser Action; you can simply do something when you click on it, or you can have a small UI page drop down from it. You may also be interested in chrome.commands API to add keyboard shortcuts.

Here's a mock for the simplest architecture possible: a background script that swaps between 2 base domains on click (note that it needs "activeTab" permission).

var BASE1 = "";
var BASE2 = "";

// From
function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

function baseToRegExp(base) {
  return new RegExp("^(https?:\/\/[^\/]*)(" + escapeRegExp(base) + ")/");

var BASE1RegExp = baseToRegExp(BASE1);
var BASE2RegExp = baseToRegExp(BASE2);

chrome.browserAction.onClicked.addListener(function(tab) {
  if (tab.url.match(BASE1RegExp)) {
    chrome.tabs.update(, {
      url: tab.url.replace(BASE1RegExp, "$1"+BASE2+"/")
  } else if (tab.url.match(BASE2RegExp)) {
    chrome.tabs.update(, {
      url: tab.url.replace(BASE2RegExp, "$1"+BASE1+"/")

There are many beginner tutorials for Chrome Extensions; I would recommend starting at the Overview page.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download