Moment For Technology

Description of Chrome extension

Posted on Aug. 6, 2022, 1:48 a.m. by Bruce Moreno
Category: The front end Tag: chrome

A list,

1. What is it?

As the name suggests, an extender is an application that extends the capabilities of a browser.

It is based on Web technologies (such as HTML, JavaScript, and CSS) and can do things that browsers cannot do.

2. What can be done

Including but not limited to the following:

  • Customize toolbars
  • Desktop notification
  • TAB page control
  • Web control
  • Bookmark control
  • Network request control
  • Access control
  • Event monitoring
  • Configure shortcut Keys
  • Right-click menu control
  • The messaging

3. For example

Many, many, many have been installed on my browser for nearly twenty years. Here's a list of common front ends:

4. File introduction

Basic Contents:

MyExtension ├ ─ the manifest. Json / / must ├ ─ imgs / / must not │ ├ ─ icon1. PNG │ ├ ─ icon2. PNG │ └ ─ icon3. PNG ├ ─ popup. The HTML / / not must ├ ─ Popup.js // Not required ├─ other files // not required

Ha, that is to say, only one file is required, you can write an extension, simple.

The required file is the manifest.json file.

Second, start development

1. Hello World

Json file. This file should contain some required fields:

Manifest_version: Represents the manifest file version. Currently, you can only fill in 2 and 3. Note that 1 is rarely supported. The browser uses this value to specify what functionality the version has.

Name: name of the plug-in.

Version: plug-in version.

Place the manifest.json file in a folder. You've already written your first program.

2. Hello World installation

On the extension tool management page of your browser, enter Chrome :// Extensions/in the address box, start the developer mode, click to load the decompressed extension program, and select the directory where the extension tool resides to install it. Alternatively, drag the folder directly to the admin page. Then turn on the program switch:

Great, you've developed a Google extension and are ready to use it!

If you want to package, there is a button package extension in the picture above, click it to upload your file package (there is an input box is optional input private key file, the first time do not need to fill, he is mainly used for update). I used to drag packaged files directly into the extension to run, but now I drag them in and install but can't open the application, because it now requires that only uploaded Google Store files can be opened. How to upload because of the need to bind the bank card to spend money to register, I will not talk about here.

3. Make a functional plugin

In order to quickly understand the extension program, Hello World developed above is a useless plug-in without any functions, so how to make a real plug-in?

Step 1: Understand the configuration of the manifest.json file.

Total about 50 configurations, or more. However, for most developers, many configurations are not commonly used. If you want to know all of them, go to the official website. Here I will briefly introduce some of the most common ones.

"Name ": "My Extension", "version": "1.0",// version string // The proposed field "default_locale": "en", // internationalization support "description": "A plain text description", "ICONS ": {"16": "Icon16.png ", // Site icon "32" on the extension page: "icon32.png", // Windows computers usually need this size. Providing this option will prevent size distortion caused by the reduction of the 48x48 option. "128": "icon128.png" // display at installation time and in Chrome Webstore}, // Choose one or both, or do not provide "browser_action": {... }, "page_action": {... }, "app": {... }, // Provide "background" as needed: {// Persistent background JS or background pages // recommend "persistent": false,}, "content_scripts": [{...}], // omnibox: {// address bar quick search "keyword": "aString"}, // multifunction address bar "permissions": ["tabs"], // A set of permissions "commands" to be used within the extension: {... },// keyboard shortcut "web_accessible_resources": ["js/inject.js"],// a list of plugin resources that can be accessed directly from the normal page. If not set, it cannot be accessed directly from the "minimum_chrome_version": "VersionString ",// The extension requires the minimum supported version of Chrome "offline_enabled": True, // specifies whether the extension supports offline "chrome_url_overrides":// overrides the browser's default page {// overrides the browser's default newtab mining plug-in with "newtab": "Newtab.html"}, // a bit less common "devtools_page": "devtools. HTML ", // devTools page entry, note that only one HTML file, not JS file "homepage_url": "http://path/to/homepage",// This extension's homepage" options_ui": {"page": "options.html", // add some default styles, recommend using "chrome_style": true }, ... }Copy the code

Using the above configuration, you can already develop many programs with specific functions.

There are a few that I need to highlight because they have special capabilities and are very common and key: background, content_scripts, injection-scripts, Browser_Action, permissions


Background can be configured with a page or js that starts when the browser is opened and runs until the browser is closed (when the plug-in is started).

So this is where you put code that runs as soon as the browser starts, runs all the time, or needs to listen for browser events.

{... {// Specify a web page, which can be imported via a relative path to js "page": "./ HTML /background.html" // Specify several js files "scripts": ["./js/background.js"]}}Copy the code

Background has high permissions, can call almost all Chrome extension apis (except DevTools), and has the ability to cross domains directly. So the frequency is relatively high.

Javascript normally listens for browser events:

Use Chrome-Extension :// /xx.html to open the background page directly


The content_scripts configuration can inject scripts (including JS and CSS) into the page, where JS does not conflict with the page script (in a different environment scope than the Web's JS); That is, it shares the DOM with the original page, but not the JS (such as a JS variable).

Content_scripts configures the JS scope shared between each item, and the JS within each item can inject multiple and share scopes.

For example: When opening any web page, run other.js, when opening baidu search home page, change the color of the search button to red, and add click events:

The above example hits two rules, injecting content.js, content2.js, and other.js in sequence.

Content-scripts has limited access to the Chrome API and can only access the following four apis:

  • chrome.extension(getURL , inIncognitoContext , lastError , onRequest , sendRequest)
  • chrome.i18n
  • chrome.runtime(connect , getManifest , getURL , id , onConnect , onMessage , sendMessage)

If additional apis are needed, they can be passed by communication via background.js.


Content-scripts can usually only manipulate the DOM, but cannot interact with the JS of the original page. Ject-scripts solves this problem.

Inject -scripts Is implemented by inserting script tags into original pages through content-scripts and dynamically importing JS resources.

For example:

The bdUser variable is available globally after baidu page login. It cannot be accessed directly through contentJs, but inject-scripts can be accessed directly.

Note that web_accesSIBLE_resources must be configured to inject JS resources into web pages. The value is the resource path data to be imported.


Browser_action can be configured with a popover page. Its configuration includes an icon, title, and a relative path to the popup page. The icon appears in the top right corner of the browser and when clicked pops up a pop-up window that closes when you leave the page.

Main characteristic is that fully customizable page, adaptive size, can interact with the user quickly and easily, statement cycle short, permissions, and can by chrome. The extension. GetBackgroundPage () direct access to the background of global variables.

Example: Click options to change baidu theme background color.


This is easier. When you find an API that you don't have permission to use, check to see if it is configured. Common permissions include:

  • Access to web pages
  • The local store
  • Web request
  • The label
  • notice
  • Right click
  • , etc.
{... "permissions": ["tabs", // notifications", // webRequest", // web request "webRequestBlocking", "storage", // plugin local storage...// etc.]}Copy the code

Relationship diagram between background, Content, Inject and PopUp:

Step 2: Learn about the Chrome API.

Chrome provides a number of special-purpose apis for extensions. There are many, but we don't have to remember all of them. At the beginning, we just need to have an understanding of most of the apis, and then we can find out how to use them during development. Exceptions are, of course, partners who like to delve deeper and develop more complex programs.

I will make a certain introduction to the API involved in this article, but THE EXPLANATION of API is not the focus of this article, and there are many APIS I do not understand and use, also dare not make a summary here, or by yourself.

Step 3: Know how to communicate.

It mainly refers to the communication between background, content_scripts, inject-scripts, and Browser_action (popup).

Communication between Popup and Backgrobaund

Popup can call global JS variables and methods in the background directly, or access the DOM of the background directly:

var bg = chrome.extension.getBackgroundPage(); bg.params(); // Access the bg variable, not the local bg.fn(); . / / access method of bg console log (bg) document. The body. The innerHTML); // Access the DOM of bgCopy the code

Background does not usually visit popup data, if the popup is on, can also use chrome. The extension. GetViews access to playing the window:

var views = chrome.extension.getViews({type:'popup'});
if(views.length  0) { console.log(views[0].location.href); }
Copy the code
Popup or Backgrobaund communication to Content

Popup or Backgrobaund sends a message to content:

Message can be any type of variable and does not require JSON parsing. You need to specify which TAB to send the request to.

Content sends a message to Backgrobaund or Popup:

Communication between injectJs and Content

There are 3 ways:

  1. Through the window. PostMessage
  2. This is done by customizing DOM events
  3. localStorage

The first is the same as when the front end used the iframe tag:

Window. postMessage({"test": 'Hello! '}, '*');Copy the code


window.addEventListener("message", function(e) { console.log(; }, false);
Copy the code

The second is a bit trickier, requiring a custom event that is bound to a hidden div and passed through the hidden div:

Inject - in the script:

var customEvent = document.createEvent('Event'); customEvent.initEvent('myCustomEvent', true, true); function fireCustomEvent(data) { hiddenDiv = document.getElementById('myCustomEventDiv'); hiddenDiv.innerText = data hiddenDiv.dispatchEvent(customEvent); } fireCustomEvent(' Hello, I'm normal JS! ');Copy the code

The content - script. In js:

var hiddenDiv = document.getElementById('myCustomEventDiv'); if(! hiddenDiv) { hiddenDiv = document.createElement('div'); = 'none'; document.body.appendChild(hiddenDiv); } hiddenDiv.addEventListener('myCustomEvent', function() { var eventData = document.getElementById('myCustomEventDiv').innerText; Console. log(' Received custom event message: '+ eventData); });Copy the code

This approach is very unfriendly.

The third type of local storage, you have to be careful about asynchrony, you can get this one before you get that one.

The sendMessage communication method described above is called short links. Chrome also provides a long connection method, which is similar to WebSocket. You can view the API usage directly.

Table of Communication Methods (horizontal view) :

inject content popup background
inject window.postMessage

content window.postMessage

chrome.runtime.sendMessage chrome.runtime.sendMessage
popup chrome.tabs.sendMessage chrome.extension.getBackgroundPage
background chrome.tabs.sendMessage chrome.extension.getViews
Once you've reached this point, you've got the ability to develop a great plugin, so give it a try.
About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.