preface

πŸ˜‹πŸ˜‹πŸ˜‹ Hey everyone ~~

The author of the last section briefly explained how to develop a Hello Extension from scratch without JS logic, but most plug-ins are not just static pages. To enable, you need to have existing logic.

Chrome plug-ins are made up of different but interrelated components. Components can include background scripts, content scripts, options pages, UI elements, and various logic files.

Chrome plug-ins are created by Web technologies: HTML, CSS, JavaScript. The component composition of a plug-in will depend on its functionality, rather than having to write all the components.

The writer should start with input

Data state saving function realization

Create the manifest. Json

Write the plug-in first by creating the manifest.json file

{
    "manifest_version": 2."name": "Data record"."version": "1.0"."description": "Record data in real time using background"
    "browser_action": {
        "default_popup": "popup.html"."default_icon": {
            "16": "imgs/16.png"."32": "imgs/32.png"."48": "imgs/64.png"."128": "imgs/128.png"}}},Copy the code

Popup. HTML and popup. Js

Jquery is referenced here for code purposes


      
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <script src="http://open.sojson.com/jquery/jquery-3.2.1.min.js"></script>
    <script src="popup.js"> </script>
</head>
<body style="width:300px ; height:300px">
    <h1>Digital change</h1>
    <input type="text" id="input" value="0">
    <button id="btn">+ 1</button>
</body>
</html>
Copy the code
let count = 0;
$(function(){$('#input').val(count);
    $('#btn').click(function(){
        count = count+1;
        $('#input').val(count);
    });
})
Copy the code

At this point, install the plug-in and click the +1 button to change the input content.

But, be careful ~~

When you close the plug-in popover and reopen it, the number is zero again. This is not a good thing, because the plugin does not save the user’s state of use. To solve this problem, we would like to have a website like background dedicated to storing data, or saving the state. This is where the background field comes in

Add background

Add a background field to the manifest and introduce the background.js file.

{"background": {// Optional attributes "scripts": ["background.js"], "persistent": false // non-persistent},}Copy the code

Background is an optional field in the manifest. Register background, which can be interpreted as the plug-in registers a background script/website running in the browser, and analyzes the registered script to find the events it needs to listen for, etc., irrelevant to the current page. The persistent attribute indicates the persistence of the script.

background

Backgrounnd has the following properties:

  • Page. Background script home page. On the home page, there are references to scripts, which typically have a script that manages the plug-in’s various interactions and listens for browser behavior, usually namedbackground.js.
  • If scripts.pageNo HTML file is imported, thenscritsCertain scripts need to be introduced. ifpageIf HTML files are introduced, public scripts such as AIxOS, jquery, etc. are introduced to the page
  • Persistent. (true | false), the background of the script and event page background page, respectively. As for thetrueIs a persistent script, and its life cycle is the same as that of the browser. As for thefalseIs a non-persistent script. It runs when the page is active. If it does not run, the script will automatically kill the active page after a few seconds to release system resources. When I need to reload again.

The author recommends using false in general to avoid wasting system resources. Persistent plug-ins are generally plug-ins that need to use the Chrome. webRequest API to block or modify web requests.

BackgroundJS write

Since background stores state, all we need to do here is add a line of code

var count = 0
Copy the code

Note that var is used here, not let. Background is a background page, and let is block-level scoped. So you can’t access variables.

At this point, we refresh the plug-in by clicking the +1 button while closing the open plug-in popup, and the data state will be saved.

Congratulations πŸ’, we can now add logic to the page and save state via background configuration

Inject some of your inspiration into the web

A Google search for Funny Chrome Extension will reveal a number of interesting add-ons, such as a layer of funny dogs that essentially inject scripting into a web page. How does a browser plugin implement script injection? The answer is Content Scripts.

Content scripts

The plugin reads and writes Content Scripts to the page the browser is currently visiting. Content Scripts contain JavaScript executed in the context of a page that has been loaded into the browser. Content Scripts can read and modify the DOM of the page currently accessed by the browser.

Content Scripts can communicate with plug-ins by using the Storage API and to exchange information and store values.

Switch to your computer page, go to vscode, and add a content.js to the plugin library:

$('button').css('background'.'green')
Copy the code

Add a “liveable color” to the search button on NPM’s official website, configure the manifest, and add content_scripts:

{
    ... // 省η•₯
    "content_scripts": [ // ζ•°η»„οΌŒδΈεŒι‘΅ι’ζ³¨ε…₯η­–η•₯δΌšζœ‰ζ‰€δΈεŒ
    {
      "matches": [
        "https://www.npmjs.com/*"
      ],
      "js": ["jquery-2.1.3.min.js", "content.js"]
    }
}
Copy the code

Matches denotes the site that matches the elements of the array, js denotes the script that needs to be inserted, and is continuously loaded from left to right.

Once you’re done, refresh the plugin and go to the NPMJS official website. You’ll find that the Search button turns green, indicating that the script was successfully injected.

conclusion

Through the introduction of the plugin logic, you can see that the core of the Chrome plugin is three parts:

  • popup
  • content scripts
  • background

In the next section, you’ll see how these three core parts communicate from the perspective of Chrome plug-in communication.

Good night, ~