2

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.

Brian Smith
  • 117
  • 8
  • 2
    Next time you write a question, don't include "noise" describing how you're sure this question is bad. It's not helping your case. See [How to Ask](https://stackoverflow.com/help/how-to-ask). – Xan Sep 30 '16 at 11:48
  • Got to this question because I was just looking for a chrome extension to change a base url for me. You can just download [this extension](https://chrome.google.com/webstore/detail/requestly-redirect-url-mo/mdnleldcmiljblolnjhpnblkcekpdkpa?hl=en) to do just that. – takanuva15 Apr 13 '21 at 18:31

1 Answers1

3

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 = "example.com";
var BASE2 = "example.org";

// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
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(tab.id, {
      url: tab.url.replace(BASE1RegExp, "$1"+BASE2+"/")
    });
  } else if (tab.url.match(BASE2RegExp)) {
    chrome.tabs.update(tab.id, {
      url: tab.url.replace(BASE2RegExp, "$1"+BASE1+"/")
    });        
  }
});

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

Xan
  • 74,770
  • 16
  • 179
  • 206