preface

Recently, I am studying some interesting things. A few days ago, I played a wechat chat robot to beautify pictures. Today, I want to write a browser plug-in. Don’t say anything and get started.

The body of the

To write a browser plug-in, it’s easy. Just create a folder and make sure it has a manifest.json file underneath it, as you would with any other development project.

This is the structure of my project:

Note: there is a glitch here, mainfest.json file name must be written correctly, otherwise it will report an error when using developer mode to load the plugin.

Next is a basic configuration

{
    "name": "IRON MAN"."version": "1.0.0"."description": "I am iron man"."manifest_version": 2."background": {
        "scripts": [
            "background.js"]."persistent": false
    },
    "icons": {
        "16": "images/4.png"."48": "images/4.png"."128": "images/4.png"
    },
    "page_action": {
        "default_popup": "popup.html"."default_icon": "images/4.png"}}Copy the code

Once configured, you can add a plug-in to your browser. It’s as simple as that

You can access the Plugin Management page from the top right menu -> More Tools -> Extensions, or directly enter Chrome :// Extensions in the address bar.

Check the developer mode to load the plugin directly as a folder, otherwise you can only install. CRX files.

manifest.jsonConfiguration:

In manifest.json, manifest_version, name, and versionare essential, while description and ICONS are recommended.

Here is a paste from the big guy there paste to the analysis:

{
	// 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 plug-in
	"version": "1.0.0".// Plug-in description
	"description": "Simple Chrome extension Demo".// Use the same size icon
	"icons":
	{
		"16": "img/icon.png"."48": "img/icon.png"."128": "img/icon.png"
	},
	// The background JS or background page will always be resident
	"background":
	{
		// If you specify JS, a background page will be generated automatically
		"page": "background.html"
		//"scripts": ["js/background.js"]
	},
	// Set the icon in the upper right corner of the browser. Browser_action, Page_Action or APP must be selected
	"browser_action": 
	{
		"default_icon": "img/icon.png".// The title of the hovering icon, optional
		"default_title": "This is a sample Chrome plugin"."default_popup": "popup.html"
	},
	// An icon that is displayed only when certain pages are opened
	/*"page_action": {"default_title": "pageAction", "default_popup": "popup.html"},*/
	// Need to inject the JS directly into the page
	"content_scripts": [{//"matches": ["http://*/*", "https://*/*"],
			// "
      
       " matches all addresses
      
			"matches": ["<all_urls>"].// Multiple JS are injected in sequence
			"js": ["Js/jquery - 1.8.3. Js"."js/content-script.js"].// JS injection can be arbitrary, but CSS must be careful, because careless can affect the global style
			"css": ["css/custom.css"].Optional values: "document_start", "document_end", or "document_idle". The last one indicates that the page is idle, and the default is document_idle
			"run_at": "document_start"
		},
		// 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 request
	"permissions":
	[
		"contextMenus".// Right-click the menu
		"tabs"./ / label
		"notifications"./ / notice
		"webRequest"./ / web request
		"webRequestBlocking"."storage".// Plugin local storage
		"http://*/*".// A website accessible from executeScript or insertCSS
		"https://*/*" // A website accessible from executeScript or insertCSS].// A list of plug-in resources that can be accessed directly from a normal page
	"web_accessible_resources": ["js/inject.js"].// Plugin home page, this is very important, do not waste this free advertising space
	"homepage_url": "https://www.baidu.com".// Override the browser default page
	"chrome_url_overrides":
	{
		// Overrides the browser's default new TAB page
		"newtab": "newtab.html"
	},
	// plugin configuration page before Chrome40
	"options_page": "options.html".// Chrome40 after the plugin configuration page, if both write, the new version of Chrome only recognize the latter 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 can only point to an HTML file, not JS file
	"devtools_page": "devtools.html"
}
Copy the code

How do I implement the functions of the two plug-ins step by step

1. Register listening events

Register listening events in the extender’s background script: listening is triggered after the script loads

chrome.runtime.onInstalled.addListener(function () {
    chrome.storage.sync.set({ color: '#e84f20' }, function () {
        console.log("The orange color of shrimp skin.");
    });
     chrome.declarativeContent.onPageChanged.removeRules(undefined.function () {
        chrome.declarativeContent.onPageChanged.addRules([{
            conditions: [new chrome.declarativeContent.PageStateMatcher({
                pageUrl: { hostEquals: 'www.baidu.com'}})],actions: [new chrome.declarativeContent.ShowPageAction()]
        }]);
    });
});
Copy the code

2. Register permission

Because we use the Chrome. storage API in background, we need to register it in manifest.json

   "permissions": [
        "storage"."declarativeContent"."tabs"."activeTab"."contextMenus",].Copy the code

3. Refresh our extensions on the extensions page

Click on the view background page to see the print

4. Introduce ICONS

You can also see the iron Man icon in the screenshot above. So here are two points to note:

  • For uncompressed extensions, only PNG ICONS can be used.
  • ICONS can be adapted to different sizes, so if you’re lazy, use all one.

5. Introduce the PopUp page

I wrote two simple functions in the page: let the page color, let the page color restore.

<! DOCTYPEhtml>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <style>
        .btn {
            height: 50px;
            background-color: #e84f20;
            border-radius: 4px;
            line-height: 50px;
            text-align: center;
            padding: 0 5px;
            color: #fff;
            margin-right: 20px;
        }

        .wrapper {
            width: 500px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    </style>
</head>

<body>
    <div class="wrapper">
        <Button id="btn" class="btn">Click to turn shrimp red</Button>
        <Button id='clear' class="btn">restore</Button>
    </div>
    <script src="./popup.js"></script>
</body>

</html>
Copy the code

The js file is as follows:

let changeColor = document.getElementById('btn');
let clear = document.getElementById('clear');
chrome.storage.sync.get('color'.function (data) {
    changeColor.style.backgroundColor = data.color;
    changeColor.setAttribute('value', data.color);
});
changeColor.onclick = function (element) {
    let color = element.target.value;
    chrome.tabs.query({ active: true.currentWindow: true }, function (tabs) {
        chrome.tabs.executeScript(
            tabs[0].id,
            { code: 'document.body.style.backgroundColor = "' + color + '"; ' });
    });
};
clear.onclick = (ele) = > {
    chrome.tabs.query({ active: true.currentWindow: true }, function (tabs) {
        let color = '#fff'
        chrome.tabs.executeScript(
            tabs[0].id,
            { code: 'document.body.style.backgroundColor = "' + color + '"; ' });
    });
}
Copy the code

Use Chrome.storage.sync.get to get the color in memory. Using chrome. Tabs. ExecuteScript to page into the script.

Note that all chrome apis we use need to be configured in manifest.json

Now we can play our plugin on baidu page!

What happens when you click on it

You can also restore the color.

So the first function to color and restore the site is done. Next I want to make a translation function.

6. Continue adding background scripts

   chrome.contextMenus.create({
        id: "9527".contexts: ['selection'].title: 'Let Iron Man Translate: % S'.// Displays the text. This parameter is required unless it is of the "separator" type. If the type is "selection", use %s to display the selected text
    })
    console.log(chrome.contextMenus)
    chrome.contextMenus.onClicked.addListener((info, tab) = > {
        const query = info.selectionText;
        const url = "https://fanyi.baidu.com/translate?#est/zh/" + query;
        chrome.tabs.create({ url: url });
    })
Copy the code

The function of this script is to create a right-click action menu on the page, as shown in the figure below

We can add a listening event to do something when we click on the corresponding url. In the example, I add a translation function to the selected text, jump to Baidu translation by listening to click events, and bring the selected text to the past for translation.

Note here, too: The contextMenus need to be registered in manijest. Json.

At this point our functionality is fully implemented. Because the ingenuity is not agile enough, there is no more practical function research and development. I hope you can give me some ideas ~~

The last

Some of the more complete online tutorial +API

Google Plug-in development API

Plug-in Development Guide

Finally, thank you!