primers

Follow Chrome Extensions: What are extensions? “, followed by an introductory tutorial.

An introduction to

Extensions are made up of different but cohesive components. Components can include background scripts, content scripts, option pages, UI elements, and various logical files. Extension components are created using Web development techniques: HTML, CSS, and JavaScript. The component of the extension will depend on its functionality and may not require all options.

To start, create a new folder to store the extension files.

The full extension can be downloaded here.

Create the manifest

The extension starts with manifest. Create a file called manifest.json with the following code.

{
  "name": "Getting Started Example"."description": "Build an Extension!"."version": "1.0"."manifest_version": 3
}
Copy the code

In the current state, the directory containing the manifest file can be added as an extension in developer mode.

  1. Navigate to thechrome://extensionsThe extension management page is displayed.
    • Or click the Extensions menu button and select Manage Extensions at the bottom of the menu to open the page.
    • Or click on the Chrome menu, hover over More Tools and select Extensions.
  2. Click the switch next to Developer Mode to turn on Developer mode.
  3. Click the Load Unpacked button and select the extension folder.

Clicking! The extension has been successfully installed. Because ICONS are not included in the manifest, a generic icon will be created for the extension.

Add functionality

The extension is now installed, but it can’t do anything now because we haven’t told it what to do or when to do it. We solve this problem by adding some code to store the background color value.

To do this, we need to create a background script and add it to the extension’s MANIFEST. Start by creating a file called background.js in the extension’s directory.

{ "name": "Getting Started Example", "description": "Build an Extension!" , "version": "1.0", "Manifest ": 3+ "background": {
+ "service_worker": "background.js"
+}
}
Copy the code

As with many other important components, background scripts must be registered in the Manifest. Registering a background script in the manifest tells the extension which file to reference and how it should behave.

Chrome is now aware that the extension includes a service. When you reload the extension, Chrome will scan the specified file for additional instructions, such as important events to listen for.

Once installed, this extension requires information from persistent variables. Start by including a listener on runtime.onInstalled in the background script. In the onInstalled listener, the extension sets a value using the Storage API. This will allow multiple extension components to access the value and update it.

let color = '#3aa757';

chrome.runtime.onInstalled.addListener(() = > {
  chrome.storage.sync.set({ color });
  console.log('Default background color set to %cgreen'.`color: ${color}`);
});
Copy the code

Most apis, including the Storage API, must be registered under the Permissions field in the Manifest for extensions to use them.

{ "name": "Getting Started Example", "description": "Build an Extension!" , "version": "1.0", "Manifest_version ": 3, "background": {"service_worker": "background. Js"},+ "permissions": ["storage"]
}
Copy the code

Return to the extension Management page and click the Reload link. A new field Inspect Views is available with a link in blue: Background Page.

Default background color set to green

The translator note

Try Chrome version 90.0.4430.85 (official) (x86_64) and find some discrepancies:

  • The clickable link is the Service Worker and becomes invalid after a certain amount of time, so you need to click the Reload link.

Introducing user interfaces

Extensions can have multiple forms of user interfaces; This one will use popup. Create and add a file named popup.html to the extension’s directory. This extension uses buttons to change the background color.

<! DOCTYPEhtml>
<html>
  <head>
    <link rel="stylesheet" href="button.css">
  </head>
  <body>
    <button id="changeColor"></button>
  </body>
</html>
Copy the code

As with background scripts, this file must be declared in the manifest so that Chrome can display it in the extension popup window. To do this, add an action object to the manifest and set popup.html as the value of the action’s default_popup attribute.

{ "name": "Getting Started Example", "description": "Build an Extension!" , "version": "1.0", "Manifest_version ": 3, "background": {"service_worker":" background-js "}, "permissions": ["storage"],+ "action": {
+ "default_popup": "popup.html"
+}
}
Copy the code

The HTML for this pop-up window references a CSS file called button.css. Add another file to the extension’s directory, name it appropriately, and add the following code.

button {
  height: 30px;
  width: 30px;
  outline: none;
  margin: 10px;
  border: none;
  border-radius: 2px;
}

button.current {
  box-shadow: 0 0 0 2px white,
              0 0 0 4px black;
}
Copy the code

The designation of toolbar ICONS is also contained under the action default_icons field. Download the image file here, unzip it, and place it in the extension’s directory. Update the manifest so that the extension knows how to use images.

{ "name": "Getting Started Example", "description": "Build an Extension!" , "version": "1.0", "Manifest_version ": 3, "background": {"service_worker":" background-js "}, "permissions": ["storage"], "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"
+}}}Copy the code

The extension can also display images on the extension administration page, permission warnings, and Favicon. These images are specified under the ICONS field of the manifest.

{ "name": "Getting Started Example", "description": "Build an Extension!" , "version": "1.0", "Manifest_version ": 3, "background": {"service_worker":" background-js "}, "permissions": ["storage"], "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" } },+ "icons": {
+ "16": "/images/get_started16.png",
+ "32": "/images/get_started32.png",
+ "48": "/images/get_started48.png",
+ "128": "/images/get_started128.png"
+}
}
Copy the code

If you reload the extension at this stage, it will contain the provided icon instead of the default placeholder, and clicking on this action will open a pop-up window with a default color button.

The last step in the popup UI is to add color to the button. Create a file named popup.js in the extension directory and add the following code.

// Initialize button with user's preferred color
let changeColor = document.getElementById("changeColor");

chrome.storage.sync.get("color".({ color }) = > {
  changeColor.style.backgroundColor = color;
});
Copy the code

This code grabs the button from popup.html and requests the color value from the store. The color is then used as the background for the button. Add a popup.js script tag to popup.html.

<! DOCTYPE html> <html> <head> <link rel="stylesheet" href="button.css"> </head> <body> <button id="changeColor"></button>+ 
  </body>
</html>
Copy the code

Reload the extension to view the green button.

Logic layer

The extension now has a custom icon and a pop-up window that colors the pop-up button based on the value saved to the extension store. Next, it requires further user interaction logic. Add the following to the end of the popup.js file.

// When the button is clicked, inject setPageBackgroundColor into current page
changeColor.addEventListener("click".async() = > {let [tab] = await chrome.tabs.query({ active: true.currentWindow: true });

  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    function: setPageBackgroundColor,
  });
});

// The body of this function will be executed as a content script inside the
// current page
function setPageBackgroundColor() {
  chrome.storage.sync.get("color".({ color }) = > {
    document.body.style.backgroundColor = color;
  });
}
Copy the code

The updated code adds a click event listener to the button, which triggers a programmatically injected content script. This will make the background color of the page the same as the color of the button. Using programmatic injection allows users to invoke content scripts instead of automatically inserting unwanted code into web pages.

Manifest will require activeTab permission to allow extensions temporary access to the current page, and scripting permission to use the scripting API’s executeScript methods.

{
  "name": "Getting Started Example",
  ...
+ "permissions": ["storage", "activeTab", "scripting"],. }Copy the code

The extension is now complete! Reload the extension, refresh this page, open the pop-up window and click the button to turn it green! However, some users may wish to change the background to a different color.

Provide options for the user

The extension currently only allows users to change the background to green. Including an options page gives users more control over the functionality of the extension, further customizing their browsing experience.

Start by creating a file named options.html in the directory and containing the following code.

<! DOCTYPEhtml>
<html>
  <head>
    <link rel="stylesheet" href="button.css">
  </head>
  <body>
    <div id="buttonDiv">
    </div>
    <div>
      <p>Choose a different background color!</p>
    </div>
  </body>
  <script src="options.js"></script>
</html>
Copy the code

Register the options page in manifest.

{
  "name": "Getting Started Example",
  ...
+ "options_page": "options.html"
}
Copy the code

Reload and click DETAILS.

Scroll down the details page and select Extension Options to view the options page.

The last step is to add the option logic. Create a file called options.js in the extension’s directory and add the following code.

let page = document.getElementById("buttonDiv");
let selectedClassName = "current";
const presetButtonColors = ["#3aa757"."#e8453c"."#f9bb2d"."#4688f1"];

// Reacts to a button click by marking the selected button and saving
// the selection
function handleButtonClick(event) {
  // Remove styling from the previously selected color
  let current = event.target.parentElement.querySelector(
    `.${selectedClassName}`
  );
  if(current && current ! == event.target) { current.classList.remove(selectedClassName); }// Mark the button as selected
  let color = event.target.dataset.color;
  event.target.classList.add(selectedClassName);
  chrome.storage.sync.set({ color });
}

// Add a button to the page for each supplied color
function constructOptions(buttonColors) {
  chrome.storage.sync.get("color".(data) = > {
    let currentColor = data.color;
    // For each color we provided...
    for (let buttonColor of buttonColors) {
      / /... Create a button with that color...
      let button = document.createElement("button");
      button.dataset.color = buttonColor;
      button.style.backgroundColor = buttonColor;

      / /... Mark the currently selected color...
      if (buttonColor === currentColor) {
        button.classList.add(selectedClassName);
      }

      / /... and register a listener for when that button is clicked
      button.addEventListener("click", handleButtonClick); page.appendChild(button); }}); }// Initialize the page by constructing the color options
constructOptions(presetButtonColors);
Copy the code

Provide four color options, and then generate a button with an onclick event listener on the options page. When the user clicks the button, it updates the color value in the extended store. Because all of the extended files extract color information from this store, no other values need to be updated.

The next step

Congratulations! The directory now has a fully functional Chrome extension, although it’s too simple.

What’s next?

  • The Chrome Extension Overview provides some support and fills in a lot of details about the Extension architecture, as well as specific concepts that developers want to be familiar with.
  • Learn about the options available for debugging extensions in the debugging tutorial.
  • Chrome extensions can access powerful apis, not just those on the open Web. The Chrome.*API documentation describes all of the apis.
  • Developer’s Guide has dozens of additional links to related documentation on creating advanced extensions.

The resources

  • Chrome Extensions : Getting started

Recently, I think of a popular TV play “Silent Truth”. I didn’t want to watch it when it was very popular, but now I think of it, I go to watch it.

Unexpectedly, when looking for resources to download, thunder prompt this play there is sensitive information, can not download.

After watching the heart feel heavy, the cost of extending justice is really big, if the average person, estimated to have given up.