How to write a Chrome Extension

Pagorn Phusaisakul
3 min readJul 28, 2022

--

I just wanna avoid msn.com after login internet, and this is the result 😜

TL;DR

You can download the source code and try it

Prerequisites

  • Google Chrome
  • Visual Studio Code (or other editor)

Step by step

Create the sample-chrome-extension folder

To store our scripts manifest.json and background.js

$ mkdir sample-chrome-extension
$ cd redirect-web-chrome-extension
$ code .

Create the manifest.json

{
"name": "Redirect Web",
"manifest_version": 3,
"version": "1.0",
"description": "Redirect from MSN.com to youtube.com",
"permissions": [
"tabs"
],
"background": {
"service_worker": "background.js"
}
}

The important part is we ask for tabs permission, and define service worker with background.js

Create the simple background.js

chrome.tabs.onUpdated.addListener(
(tabId, changeInfo, tab) => {
console.log('Updated to URL:', tab.url)
}
)
  • chrome.tabs.onUpdated.addListener() to add the Listener function
  • tab.url will be fired when a tab is updated.

Folder structure

Now, we should have the structure like this

Folder structure

Import the extension on Chrome

How to install the extension
  • Launch Chrome
  • Open the extension manager chrome://extensions/
  • Enable Developer mode
  • Click Load unpacked
  • Select folder sample-chrome-extension
Enable Developer Mode and Load unpacked

The new extension should be there

The simple extension is installed

Try to use Console

How to use Extension Console
  • Open a new tab and go to some website
  • Go back to the extension manager
  • Click service worker to open DevTools
  • Click Console tab
  • We should see log messages
Updated to URL: chrome://newtab/
Updated to URL: https://www.msn.com/th-th

Detect msn.com and update Tab URL

// background.js
chrome.tabs.onUpdated.addListener(
async (tabId, changeInfo, tab) => {
console.log('Updated to URL:', tab.url)
if (tab.url.includes('msn.com')) {
await chrome.tabs.update(tab.id, { url: 'https://youtube.com'
});

}
}
)
  • Check if URL contains msn.com
  • chrome.tabs.update to Force Tab update URL to be https://youtube.com

Reload extension and enjoy! 🎉

The result

Tip 💡

You might found this error

Error: Tabs cannot be edited right now (user may be dragging a tab).
  • Declare an async function and move your logic there
  • Use try…catch
  • Recall the function again later in catch with SetTimeout() in 50 milliseconds
// background.jsconst ERROR = 'Error: Tabs cannot be edited right now (user may be dragging a tab).'async function redirect(tabId, changeInfo, tab) {
console.log('Updated to URL:', tab.url)
try {
if (tab.url.includes('msn.com')) {
await chrome.tabs.update(tab.id, { url: 'https://youtube.com' });
}
} catch (error) {
if (error == ERROR) {
setTimeout(() => redirect(tabId, changeInfo, tab), 50);
} else {
console.error(error);
}
}
}
chrome.tabs.onUpdated.addListener(redirect)

--

--

No responses yet