Creating Chrome Extensions With TypeScript | by Enis Erbek | Jan, 2022

Change the background shade of a web page

I’ll cowl, what are extensions, the significance of TypeScript, and easy methods to create a easy chrome extension utilizing TypeScript exhibiting the required procedures step-by-step.

Extensions are small software programs that customize the browsing experience. They let users tailor Chrome functionality and behavior in many ways.

Virtually everyone seems to be utilizing extensions on their browsers, particularly for blocking these annoying advertisements.

Some examples of chrome extensions are:

  • Password managers
  • Advert blockers
  • To-do listing creators

and plenty of extra could be discovered on the Chrome Web Store.

Extensions are constructed on net applied sciences such as HTML, JavaScript, and CSS. They run in a separate, sandboxed execution surroundings and work together with the Chrome browser. Extensions allow you to “prolong” the browser by utilizing APIs to change browser habits and entry net content material.

For starters, TypeScript is a superset of JavaScript that means that it extends JavaScript. Therefore, it solves some issues that JavaScript can’t.

Many JavaScript apps are made up of hundreds of thousands of files. A single change to one individual file can affect the behavior of any number of other files, like throwing a pebble into a pond and causing ripples to spread out to the bank.

It doesn’t imply TypeScript should be used for less than giant functions. If you happen to wish to code kind safely it is a nice strategy to go.

TypeScript achieves its objectives in 3 ways:

  • Assist for contemporary JavaScript options
  • Superior kind system
  • Developer tooling help

With the assistance of TypeScript, your software can out of the blue be type-safe, straightforward to develop, straightforward to debug, object-oriented, and effectively structured.

Sufficient with the chatter, lets leap into code

To have the ability to full this tutorial you might want to have Node and npm put in.

In the course of the demonstration, you may be creating some folders and information. The ultimate folder construction might be like beneath.

In case you are prepared to alter the folder construction, you’ll have to regulate the configurations accordingly.

  • Create an empty listing and initialize a challenge through npm.
~$ mkdir medium-extension
~$ cd medium-extension
~$ npm init -y
  • Set up the required dependencies.
~$ npm set up --save-dev webpack webpack-cli
~$ npm set up --save-dev copy-webpack-plugin
~$ npm set up --save-dev typescript ts-loader
~$ npm set up --save-dev @sorts/chrome
  • Create tsconfig.json folder. The tsconfig.json file specifies the basis information and the compiler choices required to compile the challenge. Be at liberty to dig deep into configuring TypeScript initiatives from here.

"compilerOptions":
"strict": true,
"module": "commonjs",
"goal": "es6",
"esModuleInterop": true,
"sourceMap": true,
"rootDir": "src",
"outDir": "dist/js",
"noEmitOnError": true,
"typeRoots": [ "node_modules/@types" ]

  • Create directories named src and webpack and public contained in the challenge folder.

Create a webpack.config.js file contained in the webpack folder and background.ts file contained in the src folder.

const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
module.exports =
mode: "manufacturing",
entry:
background: path.resolve(__dirname, "..", "src", "background.ts"),
,
output:
path: path.be a part of(__dirname, "../dist"),
filename: "[name].js",
,
resolve:
extensions: [".ts", ".js"],
,
module:
guidelines: [

test: /.tsx?$/,
loader: "ts-loader",
exclude: /node_modules/,
,
],
,
plugins: [
new CopyPlugin(
patterns: [from: ".", to: ".", context: "public"]
),
],
;

This can direct webpack to load all .ts information by way of the ts-loader, and output a dist folder containing bundled .js information in our challenge.

  • Add construct script within the package deal.json file.

"title": "medium-extension",
"model": "1.0.0",
"description": "",
"major": "index.js",
"scripts":
"construct": "webpack --config webpack/webpack.config.js"
,

"key phrases": [],
"creator": "",
"license": "ISC",
"dependencies": ,
"devDependencies":
"ts-loader": "^9.2.6",
"typescript": "^4.5.4",
"webpack": "^5.66.0",
"webpack-cli": "^4.9.1"

Each extension has a JSON-formatted manifest file. A manifest file incorporates metadata of the entire extension software together with title, model, descriptions, content material scripts, permissions, and plenty of extra.

Create a file named manifest.json . Functions and usages of every subject within the manifest file could be discovered within the official document.


"title": "Medium Extension",
"description": "This extension is made for demonstration functions",
"model": "1.0",
"manifest_version": 3,
"permissions": [
"activeTab",
"scripting"
],
"background":
"service_worker": "background.js"

On this manifest file:

title, description, and model are the identical because the title implies.

manifest_version: determines the model of the manifest file. Which is the newest and the beneficial model in the meanwhile.

permissions: these are required permissions which can be wanted on your extension’s primary performance.

service_worker: Extensions register their background service staff typically when they’re first initialized. This configuration permits background.js functioning as a service employee. A service employee is a script that your browser runs within the background. Your extensions performance might be dealt with through a registered service employee.

We described background.js within the manifest file. We’ll create a file named background.ts and write our code kind safely, handing over the bundling and the ts -> js conversion to the webpack.

let energetic = false;

perform makeOrange(shade: string): void
doc.physique.model.backgroundColor = shade;

chrome.motion.onClicked.addListener((tab) =>
energetic = !energetic;
const shade = energetic ? 'orange' : 'white';
chrome.scripting.executeScript(
goal: tabId: tab.id ? tab.id : -1,
func: makeOrange,
args: [color]
).then();
);

On this code block, with the assistance of the chrome API, we take heed to the press occasion on the extension motion button and alter the background shade of the presently energetic tab.

Within the root listing of the challenge, run the next script.

~$ npm run construct

This can create a dist folder containing manifest.json and background.js within the challenge.

  • Navigate to the chrome://extensions in your chrome browser. And guarantee that Developer Mode is activated on the highest proper facet of the display screen.
  • Click on Load Unpacked and goal the dist folder in your challenge.

It should carry up your extension on the display screen.

  • Click on the extension icon on the fitting facet of the Chrome toolbar. And pin the extension to the toolbar.

More Posts