Chrome plug-in, everyone will install a few, like JSON formatting, Postman, page address TWO-DIMENSIONAL code and very cow force oil monkey, with a lot of, but how to write this thing, through a small demo to understand, this demo is called what are you looking at.

Making address:You see what. First see how to use, usually install plug-ins are to go to the store to download or download CRX.

Start by opening extender management

Then open developer mode in the upper right corner

At this point, you will find that there is an extra toolbar, and there is an ID and view under the plug-in, which will come later. Click on the top left corner to load the decompressed extension, and you can select the local folder. What does a plugin have next

manifest.json

The plug-in configuration file is a must.

{// this is the official release of the v3, the 2 is still used, because the 3 is not running... Manifest_version: 2, // Plug-in name" name": "What are you looking at", // Plug-in version" version": "0.0.1", // Plug-in description" description": "What you see", / / icon "ICONS" : {" 16 ":" icon. PNG ", "32" : "icon. PNG", "48" : "icon. PNG", "128" : "Icon. PNG"}, "icon. PNG "}, "background": {// v3 = "service_worker" "Default_icon ": "icon.png", "default_title": "This is a plugin for what you're looking at ", "default_popup": "popup.html"}, // need to inject the page's JS "content_scripts" directly: [{/ / can be determined according to the page address whether injection, "< all_urls >" means to match all address "matches" : [" < all_urls > "], / / multiple JS injection in sequence "JS" : [" JS/index. JS] ", "CSS" : ["style.css"], // code injection time, has three values: "Document_start ", "document_end", or "document_idle", the default document_idle means to inject "run_at" when the page is idle: }], // permissions": [" contextMenus ", / / right-click menu "tabs", / / label "notifications", / / notification "webRequest", / / web request "storage", / / plugin local storage, the browser is stored globally, "Chrome_url_overrides ": {// override the default newtab page of the browser. Momentum uses this "newtab": }, // this is the plugin configuration page" options_ui":{"page": "options.html", // Default style" chrome_style": "Default_locale ": "zh_CN", // DevTools page entry "devtools_page": "Devtools.html ", // homepage_URL: "https://www.baidu.com",}Copy the code

That’s pretty much what they use. It’s not very complicated.

background

In addition to DevTools, it can call other extension apis provided by Chrome, and the request is not cross-domain, and does not need to write cORS. In fact, there are two ways to write this:

"background": {
   "page": "background.html"
   // "scripts": ["background.js"]
},
Copy the code

scriptsWill generate an HTML page with the address ofchrome-extension://id/background.htmlIn the middle of the,idIs the id of the plug-in. The page can be accessed and closed, but one of them is running and you can’t see it yet.

Click on this to open itbackgroundDeveloper tools for debugging.

browser_action

This is the configuration of the location icon in the upper right corner of the browserdefault_iconIcon:

default_title: The title of the mouse hover

default_popup: Click the icon to pop up the page, the life cycle is relatively short, from click on to close

homepage_url

Home page address, right click on the icon

Click on this to access it

content_scripts

This is the script for the page, which can be javascript or CSS. This is the script for the page, which can be javascript or CSS. This is the script for the page, which can be javascript or CSS. Other is not not dry, can communicate with background, let the background dry.

permissions

This is the configuration of permissions, there are usage in the demo below.

options_ui

This is the configuration page for the plug-in

When you click on it, you get a popover

Because chrome_style is true, there will be a default style.

You see what

That’s the structure of the demo. It’s pretty simple.

{" Manifest_version ": 2, "name": "What are you looking at", "version": "0.0.1", "description": "What are you looking at", "ICONS ": {"16": "icon.png", "32": "icon.png", "48": "icon.png", "128": "icon.png" }, "background": { "page": "Background-html"}, "browser_action": {"default_icon": "icon.png", "default_title": "this is a plugin for what you're looking at ", "default_popup": "popup.html" }, "homepage_url": "https://www.baidu.com", "content_scripts": [ { "matches": ["<all_urls>"], "js": ["js/index.js"], "css": ["style.css"], "run_at": "document_start" } ], "permissions": [ "notifications", "contextMenus" ], "options_ui": { "page": "options.html", "chrome_style": true } }Copy the code

This is the configuration file. Look at the content_scripts

const createEl = (text) => { const textContainer = document.createElement('div'); textContainer.className = 'what-are-you-looking-at-text' textContainer.innerHTML = text; return textContainer; } window.onload = () => { let timer = null; Const textArray = [' what do you look at ', 'What do you look at ',' What do you look at ', 'What do you look at ',' What do you look at ']; timer = setTimeout(async () => { const lookAtContainer = document.createElement('div'); lookAtContainer.className = 'what-are-you-looking-at'; document.body.appendChild(lookAtContainer); for (const x of textArray) { await new Promise((resolve) => { setTimeout(() => { lookAtContainer.innerHTML = ''; lookAtContainer.appendChild(createEl(x)); resolve(); }, 3000); (})} setTimeout () = > {chrome. Runtime. SendMessage ({message: 'eldest brother you to beat the'}, (response) = > {the console. The log (' response: ' + response); }); lookAtContainer.onclick = () => { document.body.removeChild(lookAtContainer); }}, 1000); }, 10000); }Copy the code

The process is simple. After opening the page for 10 seconds, there will be a semi-transparent popover with the most commonly used greeting, and after the end of the conversation, a message will be sent to the background, “I’ve been punched.” In background, after receiving the message, it sends a message back to content_scripts that it knows and sends a browser notification that someone hit it.

chrome.runtime.onInstalled.addListener(function() { chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { console.log(request); console.log(sender); SendResponse (' I know '); Chrome. Notifications. The create (null, {type: 'basic' iconUrl: 'icon. PNG, title:' this is the title, the message: 'eldest brother you to beat the'}); }); });Copy the code

chrome.runtime.onInstalledWill be triggered when the browser starts.chrome.runtime.onMessage,chrome.tabs.onMessage,chrome.tabs.connect,chrome.runtime.connectFor eachjsBetween the main means of communication, used herechrome.runtime.onMessage.



Here is used to inform, to open in the permissions, then the computer setting allows chrome notice, just can have. Take another look at the permissions right-click menu.

"permissions": [
    "contextMenus"
]
Copy the code

Enable right-click menu permissions in the configuration file

chrome.runtime.onInstalled.addListener(function() { chrome.contextMenus.create({ "id": "contextMenu", "title": "Right-click menu ", onclick: () => {console.log(' right-click menu '); }}); });Copy the code

inbackgroundCreate a right-click menu in.

After clicking on it, it will print what you are looking at in the Background console by right clicking. See the official documentation for more details.