“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

Can you use Google chrome API to develop JS script plug-ins?

Would you use the Google Browser API to develop javascript plugins that block ads?

Can you use Google’s Browser API to develop scripting plugins that block Ajax requests from web pages?

Wait…

Whether you will or not, read this article today you will, no more nonsense, straight to the subject

One: Create a plug-in project

  1. Create a folder on your desktop and name demo
  2. Create a js folder and a manifest.json file under the demo folder.
  3. Then create content.js, popup.html, background.js, static files and so on.
  4. Finally, create an index.js file in the js folder. The final directory format is as follows
Demo / | - | CSS/style - index. CSS. | | - js/script - index js main page script | - jq. Min. Js third-party libraries script. | | - img/image address - background js/background tasks, Communication | - content. js script/plugin behavior | - manifest. Json permission statement | - popup. HTML home pageCopy the code

Two: core introduction

2.1 the manifest. Json

This is the most important and essential file in a Chrome plugin. It is used to configure all plugin-related configurations. It must be placed in the root directory. Manifest_version, name and version are essential, and Description and ICONS are recommended.

The following are some common configuration items with Chinese comments.

{
    // The version of the manifest file, this must be written and must be 2
    "manifest_version": 2.// The name of the plug-in
    "name": "demo".// Version of the plugin
    "version": "1.0.0".// Plug-in description
    "description": "Simple Chrome Extension Demo".// All ICONS are of one size
    "icons":
    {
        "16": "img/icon.png"."48": "img/icon.png"."128": "img/icon.png"
    },
    // Will always be resident background JS or background page
    "background":
    {
        If JS is specified, then a background page is automatically generated
        "page": "background.html"
        //"scripts": ["js/background.js"]
    },
    // Select browser_action, page_action, or app from the upper right corner of the browser
    "browser_action": 
    {
        "default_icon": "img/icon.png".// Icon hover when the title, optional
        "default_title": "This is an example Chrome plugin"."default_popup": "popup.html"
    },
    // An icon that is displayed only when certain pages are open
    /*"page_action": {"default_icon": "img/icon.png", "default_title": "I'm pageAction", "default_popup": "popup.html"},*/
    // You need to inject JS directly into the page
    "content_scripts": [{//"matches": ["http://*/*", "https://*/*"],
            // "
      
       " indicates that all urls are matched
      
            "matches": ["<all_urls>"].// Multiple JS are injected in order. Content. JS must import the corresponding third-party library before calling it
            "js": ["js/jq.min.js"."js/js.cookie.min.js"."content.js"].// Javascript injection can be arbitrary, but CSS should be careful, because a careless careless can affect the global style
            // "css": ["css/custom.css"],
            // The time for code injection. Optional values are "document_start", "document_end", or "document_idle", the last one is the default document_IDLE when the page is idle
            "run_at": "document_start"."all_frames": true
        },
        // This is just to demonstrate that content-script can be configured with multiple rules
        / / {
            // "matches": ["*://*/*.png", "*://*/*.jpg", "*://*/*.gif", "*://*/*.bmp"],
            // "js": ["js/show-image-content-size.js"]
        // }].// Permission application
    "permissions":
    [
        "contextMenus".// Right-click menu
        "tabs"./ / label
        "notifications"./ / notice
        "webRequest"./ / web request
        "webRequestBlocking"."storage".// Add local storage
        "http://*/*".// An executeScript or insertCSS website
        "https://*/*" // An executeScript or insertCSS website].// A list of add-on resources that can be accessed directly by a common page. If you do not set the add-on resources, you will not be able to access them directly
    "web_accessible_resources": [
         "js/jquery.min.js"."js/js.cookie.min.js"."js/main.js"."popup.html"].// Add-on home page, this is very important, don't waste this free advertising space
    // "homepage_url": "https://www.baidu.com",
    // Overwrite the default browser page
    // "chrome_url_overrides":
    / / {
        // Override the browser's default new TAB
        // "newtab": "newtab.html"
    // },
    // Plugin configuration page before Chrome40
    // "options_page": "options.html",
    // Plugin configuration page after Chrome40, if you write both, the new Chrome will only recognize the last one
    // "options_ui":
    / / {
        // "page": "options.html",
        // Add some default styles, recommended
        // "chrome_style": true
    // },
    // Register a keyword to the address bar to provide search suggestions. Only one keyword can be set
    // "omnibox": { "keyword" : "go" },
    // Default language
    // "default_locale": "zh_CN",
    // DevTools page entry, note that you can only point to an HTML file, not a JS file
    // "devtools_page": "devtools.html"
}
Copy the code

2.2 Content-scripts property in manifest.json

Content-scripts is a form of content that is injected into a page (although it is called script, it can also include CSS). With Content-scripts, you can easily inject JS and CSS into a specific page by configuration (see below for dynamic injection). The most common examples are: AD blocking, customized pages, etc.Copy the code

Content-scripts and the original page share the DOM, but not the JS. If you want to access the page JS (for example, a JS variable), this can only be done through its injected JS. Content-scripts does not have access to most of the Chrome.xxx. apis, except for the following four. The remaining apis can be called with backgroun.js if desired

1, Chrome. Extension (getURL, inIncognitoContext, lastError, onRequest, 3, Chrome. Runtime (connect, getManifest, getURL, id, onConnect, onMessage, 4, Chrome. Storage // cacheCopy the code

2.3 Background property in manifest.json (generally responsible for the communication between the plug-in and the page)

Plug-in background scripts, which have the longest life cycle of any type of page in the plug-in, open when the browser opens and close when the browser closes, so usually put the global code that needs to run all the time, on launch, in the background. Background has very high permissions to call almost all of Chrome's extension apis (except DevTools), and it has unlimited cross-domain access to any site without requiring CORS. In the configuration, background can specify a page by page, or specify a JS directly by scripts. Chrome automatically generates a default page for this JS:Copy the code
{
    // Will always be resident background JS or background page
    "background": {
        If you specify JS, you will automatically generate a background page, usually using scripts
        // "page": "background.html"
        "scripts": ["background.js"]
        "persistent": false // Load on demand}},Copy the code

2.4 Popup property in manifest.json (generally used to display basic interactive pages)

A popup is a small window of a web page that opens when the browser_Action or page_Action icon is clicked. It closes when the focus leaves the page. It is usually used for temporary interactionCopy the code

Popup can contain as much HTML content as you want, and is self-sizing. The popup page can be specified by using the default_POPup field, or by calling the setPopup() method.

Configuration mode:

{"browser_action": {"default_icon": "img/icon.png", // The title of the icon hover, optional "default_title": "This is an example Chrome plugin ", "default_popup": "popup.html"}} CopyCopy the code

It is important to note that the life cycle of popup pages is generally very short, because popup is opened by clicking on the icon, and the focus leaves and closes immediately. Do not write code that needs to run for a long time in popup.

On the permissions, it and background are very similar, they are the main differences between the different life cycle, can be directly through the chrome in the popup. The extension. GetBackgroundPage () the window object for background.

Three: communication process

–> content. Js is responsible for inserting the iframe page and controlling whether the iframe is displayed or hidden —-> Home page popup. HTML introduces corresponding JS and third-party plug-ins. Write the corresponding service logic —-> If popup. HTML needs to obtain the information of the monitoring page, it needs to communicate with background.js first because of the cross-domain iframe problem, and then background.js notifies content.js —-> Implement all the service logic of the plug-in

// The first parameter is fixed to be the id of the current plugin, because chrome.runtime is common, so you must specify the ID to pass communication // The second parameter is fixed to be an object, there is no unique value for the sender and the receiver, so you need to define unique properties. Type (send the communication type)/to (the name of the receiver) chrome. Runtime. SendMessage (chrome. Runtime. Id, {type: 'receiveFind' to: 'background', / /... Other attributes, can be customized}); / / recipient chrome. Runtime. OnMessage. AddListener (MSG = > {the if (MSG) type = = = 'getCookie' && MSG. To = = = 'background') {/ / Else if (MSG. Type === 'closeMonitor' && MSG. To === 'background') {// handle the corresponding logic} //..... });Copy the code

Four: installation process

  1. Installing a plug-in

Open the Google browser and go to more tools -> Extensions

Then, click the package Extension button

Select the Demo folder and click Pack to start

In this case, two files are generated in the Demo folder. If you want to repackage, you need to delete these two files first.

Finally, to install the packaged plug-in, select “Load unpacked Extension.”

Select the Content folder and the plug-in is installed.

supplement

Today’s technology is introduced here, you have any suggestions or want to learn what knowledge can comment below, I will look at the first time, maybe the next article is what you want to see, or what questions we can discuss, thank you, creation is not easy, please support more like, share