Creating an extension for Chrome / Opera / Vivaldi
As a developer, I often need to search for information about the tools and frameworks I use. Most of the technical resources are provided in English but some companies such as Microsoft (MSDN) also translate most of their resources in French and some other languages. As I'm located in France, I often get the French version first. Unfortunately, translations are often not very accurate so I prefer the original version.
Instead of changing the language on the website or rewriting by hand the address every time, I decided to create an extension for my favorite web browser: Opera. Opera is based on Chromium so the extension also works on Chrome and Vivaldi 😃
#How does the extension work ?
The extension injects a JavaScript file on every website. This script checks if the location is something like msdn.microsoft.com/fr-fr/
. In the case of a match, the location is changed to msdn.microsoft.com/en-us/
.
First, we need to create a manifest file. The manifest contains the name and the description of the extension, and a lot of optional declarations such as the required permissions, the list of actions in the action bar, etc. Let's create the manifest.json
file:
{
"manifest_version": 2,
"name": "Show me English!",
"description": "Redirect to English version of websites when available",
"version": "1.0",
"content_scripts": [
{
"matches": [
"http://*/*",
"https://*/*"
],
"js": [
"redirect.js"
]
}
]
}
We declare the JavaScript file to inject in the content_scripts
field. matches
allows to set the list of domains in which the scripts must be injected. In this case, we want to match all websites (protocol http or https), so we use wildcards.
Here's the redirect.js
file :
(function () {
function areEqualsIgnoreCase(a, b) {
return a.toLowerCase() === b.toLowerCase()
}
// 1\. Get the current url
// 2\. Replace the language part of the "msdn" url by en-us
// 3\. Navigate to the new url if different from the original url
var href = window.location.href;
var newHref = href.replace(/(.*.msdn.microsoft.com\/)([a-z]{2}-[a-z]{2})(.*)/i, "$1en-us$3");
if (!areEqualsIgnoreCase(href, newHref)) {
window.location = newHref;
return;
}
})();
Now we have to install the extension in the browser. For testing purposes, we can enable the developer mode. Navigate to "chrome://extensions/" or "opera://extensions/", click the button "Load unpacked extension…" and select the directory that contains the files of the extension :
The final step is to pack the extension using the button "Pack extension…" and upload it to the store.
Voilà! It's very easy to create an extension that injects a script or a style sheet on a page to extends its default behavior. You can discover how to create a more complex extension in the official documentation.
Do you have a question or a suggestion about this post? Contact me!