Chrome Extension v3— Basics, before you begin coding
Customizes Browser experience by adding functionality to the browser.
Technology Dependence: HTML, CSS, and JavaScript
Requirements: Google Chrome, VSCode/TextEditor
Architecture:
1. manifest.json
a json file, that provides the base information for the extension
{
// Required
"manifest_version": 3, // this is the latest version by Chrome
"name": "My Extension",
"version": "1.0.0", // version of the extension
Just having this file with the required fields makes the current project an extension.
To load this extension in Chrome.
- Type chrome://extensions
- Switch on Developer mode switch button on the right.
- Click on ‘Load unpacked’ and select the extension folder which cotains manifest.json.
Your new extension would appear.
chrome.action (icon, popup, tooltip, badge)
chrome.action
API controls the toolbar button for your extension in Chrome's UI. Includes :
Icon — main image used in the toolbar button. Set by the default_icon
key.
Popup — An action’s popup will be shown when the user clicks on the extension’s action button in the toolbar. The popup can contain any HTML contents you like, and will be automatically sized to fit its contents. The popup cannot be smaller than 25x25 and cannot be larger than 800x600. Set from the default_popup
property.
Tooltip — when mouse is hovered over the extension icon. Set from the default_title
field
Badge — layered text over the extension icon. Set it programmatically using action.setBadgeBackgroundColor()
and action.setBadgeText()
Declaration in manifest.json
action": {
"default_popup": "popup.html",
"default_icon": {
"16": "/images/get_started16.png",
"32": "/images/get_started32.png",
"48": "/images/get_started48.png",
"128": "/images/get_started128.png"
}
2. Background Scripts
Extension’s event handler; it contains listeners for browser events that are important to the extension. It lies dormant until an event is fired then performs the instructed logic. An effective background script is only loaded when it is needed and unloaded when it goes idle. eg.
- The extension is first installed or updated
- The background page was listening for an event,
- A content script or other extension sends a message.
- Another view in the extension, such as a popup, calls runtime.getBackgroundPage.
Once it has been loaded, a service worker keeps running as long as it is performing an action. The service worker won’t unload until all visible views and all message ports are closed.
Registering a background script in manifest:
“background”: {
“service_worker”: “background.js”
},
Filter events — Restrict listeners to the cases the extension cares about
Example of a sample background.js (regular event, event removal, with filter)
chrome.runtime.onMessage.addListener(function(message, callback) {if (message == 'hello') {
sendResponse({greeting: 'welcome!'})
} else if (message.data == "runLogic") {
chrome.tabs.executeScript({file: 'logic.js'});
} else if (message.data == "changeColor") {
chrome.tabs.executeScript(
{code: 'document.body.style.backgroundColor="orange"'});
} else if (message == 'goodbye') {
chrome.runtime.Port.disconnect();
};
});//remove listenerchrome.runtime.onMessage.addListener(function(message, sender, reply) { //do something
chrome.runtime.onMessage.removeListener(event);
});
//with filterchrome.webNavigation.onCompleted.addListener(function() {
alert("This is my favorite website!");
}, {url: [{urlMatches : 'https://www.google.com/'}]});
3. UI elements
Most extensions have a browser action or page action, but can contain other forms of UI, such as context menus, use of the omnibox, or creation of a keyboard shortcut.
Extension UI pages, such as a popup, can contain ordinary HTML pages with JavaScript logic. Extensions can also call tabs.create or window.open()
to display additional HTML files present in the extension.
4. Content Script
Extensions that read or write to web pages utilize a content script. The content script contains JavaScript that executes in the contexts of a page that has been loaded into the browser. Content scripts read and modify the DOM of web pages the browser visits.
Content scripts can access some chrome APIs directly, however they can access Chrome APIs used by their parent extension by exchanging messages with the extension and storing values using storage API.
Isolated world - A content script to make changes to its JavaScript environment without conflicting with the page or other extensions’ content Scripts. (private execution environment)
Content skip can be injected using:
- Static Declaration — using the
"content_scripts"
field in manifest. They can include JavaScript files, CSS files, or both. All auto-run content scripts must specify match patterns.
"content_scripts": [
{
"matches": ["http://*.nytimes.com/*"],
"css": ["myStyles.css"],
"js": ["contentScript.js"]
}
],
- Dynamic Injection — Beta Phase currently.
- Programmatically — useful to run in respond to events or on specific occasions. Extension needs host permissions for the page it’s trying to inject scripts into. Host permissions can either be granted either by requesting them as part of your extension’s manifest (see
host_permissions
) or temporarily via activeTab.
"permissions": [
"activeTab"
],chrome.runtime.onMessage.addListener((message, callback) => {
if (message == "runContentScript"){
chrome.scripting.executeScript({
file: 'contentScript.js'
});
}
});//or injecting a function
function injectedFunction(color) {
document.body.style.backgroundColor = color;
}
chrome.runtime.onMessage.addListener((message, callback) => {
if (message == "changeColor"){
chrome.scripting.executeScript({
function: injectedFunction,
arguments: ['orange']
});
}
});
Other important options include exclude_matches
, include_globs, exlude_globs, run_at, all_frames,
5. Options Page
Enables customization of the extension. Options can be used to enable features and allow users to choose what functionality is relevant to their needs. A user can view an extension’s options by right-clicking the extension icon in the toolbar then selecting options or by navigating to the extension management page at chrome://extensions
, locating the desired extension, clicking Details, then selection the options link.
Inclusion in manifest.json
{
"name": "My extension",
...//full page ui
"options_page": "options.html",//embedded box ui"options_ui": {
"page": "options.html",
"open_in_tab": false
},
...
}
Communication between pages
Different components in an extension often need to communicate with each other. Different HTML pages can find each other by using the chrome.extension
methods, such as getViews()
and getBackgroundPage()
. Once a page has a reference to other extension pages the first one can invoke functions on the other pages and manipulate their DOMs. Additionally, all components of the extension can access values stored using the storage API and communicate through message passing.
Saving data and incognito mode
Extensions can save data using the storage API, the HTML5 web storage API , or by making server requests that result in saving data. When the extension needs to save something, first consider if it’s from an incognito window. By default, extensions don’t run in incognito windows.