Why is 💡 a free trial version?
The environment of paid reading, on the one hand, well protects the intellectual property rights of creators, on the other hand, improves the writing motivation and content quality of creators.
My article is divided into “free version” and “paid version”. The “free version” is mainly short and quick daily experience skills and technology sharing, while the “paid version” is longer, more systematic and more detailed.
Regardless of the “free version” and “paid version”, I am carefully prepared, repeatedly verified and proofread, to ensure the quality of the content, adhere to the original.
If you are interested in the “free trial version”, please follow the author’s wechat official account “Sleeping plum and Smelling Flowers” to read the paid article.
❤️ Original writing is not easy, your support is the greatest support for the author to encourage ❤️
🌷🌷—— Try read Start —— port 🌷 port
It’s no secret that when we use Chrome, we all install plug-ins to make our work more efficient. After more than a decade of development, Chrome Extension’s technology model is very mature. On May 6, 2020, I published the React+Antd Plugin tutorial for Chrome. The Chrome plugin was developed based on the Manifest V2 version specification. On November 9, 2020, Google officially released MANIFEST V3 (MV3 for short), which provides better and more secure performance, as well as minor changes to the development specification. By the time this tutorial is written. More than a year later, MV3 is relatively stable and mature, and some of the other dependencies covered in the tutorial have undergone many version updates. Therefore, write a new version of the tutorial again, I hope to help you save time to explore, less detour, quickly start the project development.
The Demo depends on the following package versions:
Node. Js 16.13.2
The create – react – app 5.0.0
The react 17.0.2
The react – the router – dom 6.2.1
Antd 4.18.4
Node – sass 7.0.1
Sass – loader 12.3.0
Less 4.1.2
Less – loader 10.2.0
Stylus 0.56.0
Stylus – loader 6.2.0
The HTTP proxy – middleware 2.0.1
A sneak peek
Take a look at the table of contents to get an idea of what’s going on in this tutorial. Are there any problems you might encounter? Due to its length, this course is divided into two parts: Part I and Part II. It is strongly recommended to follow the following sections step by step, and it will take about 30 minutes to quickly grasp the principles and details of the whole project. In this way, when you encounter new problems in the future, you can know which link to start with.
1 Initializing a project • 1.1 Creating a project using create-React -app 5.0 • 1.2 Lite Project 2 Chrome Extension Basics • 2.1 Manifest V3 Overview • 2.2 Manifest V3 Major new features • 2.3 Composition of Chrome Extension • 2.4 Planning the directory structure generated by build • 2.5 Configuring manifest.json 3 Development structure design and Build configuration • 3.1 Development architecture Design • 3.2 Configuring WebPack • 3.2.1 Exposing webpack • 3.2.2 Support for Sass/Scss • 3.2.3 Support for Less • 3.2.4 Support for Stylus • 3.2.5 Setting path aliases • 3.2.6 Disable build projects from generating map files • 3.2.7 Set multiple entries • 3.2.8 Fixed build generated file names • 3.2.9 Set Popup to only import its own index.js • 3.2.10 Initialize project architecture files 4 Introduce Ant Design • 4.1 Install Ant Design • 4.2 Implement on-demand loading • 4.3 Custom Antd theme color (optional) 5 Popup development • 5.1 Install React-router-DOM • 5.2 Page build • 5.2.1 Popup entry file code • 5.2.2 Popup total route page code • 5.2.3 PopUP global style code • 5.2.4 POPup login page code • 5.2.5 Popup Home page code • 5.3 Viewing popup effects 6 Build project and load plug-in 7 Background Script development • 7.1 Setting rules for Pages that allow POPUp • 7.2 Why does the plugin icon not turn gray on the Disabled pageCopy the code
• 8.2 Developing Content Script with Ant Design • 8.3 Viewing content component effects • 8.4 Loading the plugin's own static image resources (Optional) • 9.1 Extracting ANTD Global Reset Styles • 9.2 Content introducing extracting ANTD - DIY styles • 9.3 Separate references to Ant Design component JS and CSS 10 Debug Content Script 11 API requests in a development environment • 11.1 Background Pages does not support XMLHttpRequest (AXIOS) • 11.2 Mock requests using mock.js and mockjs-fetch (optional reading) • 11.3 Setting the reverse proxy request for the development environment • 11.4 Encapsulating the API and FETCH business logic • 11.5 Canceling the mock.js mock request • 11.6 Delegating background Script to complete the API request • 11.7 Implementing the POPup page API request • 11.8 API requests for implementing Content Script • 11.9 Summary of Key Points 12 Other Remarks • 12.1 Permission Permission configuration • 12.2 Inserting JS to the target page • 12.3 Service Worker debugging • 12.4 Popup page debugging • 12.5 Simplified final build files • 12.6 GitHub address 13 ConclusionCopy the code
1 Initialize the project
1.1 Create a project using create-react-app 5.0
To find an appropriate directory, execute:
npx create-react-app react-crx-v3
Copy the code
The react-crx-v3 at the end of the command is the name of the project, which can be changed.
Create-react-app has released 5.0.0 at the time of writing this tutorial.
You are running create-react-app 4.0.3 which is behind the latest release (5.0.0)Copy the code
If you are using create-react-app, you need to clear the NPX cache and run the following command:
npx clear-npx-cache
Copy the code
Then run NPX create-react-app react-crx-v3 to create the project.
Wait a moment to complete the installation. After the installation is complete, you can start the project using NPM or YARN.
Go to the project directory and start the project:
CD react-crx-v3 yarn start (or use NPM start)Copy the code
If yarn is not installed, you can go to the Yarn Chinese website to install yarn:
yarn.bootcss.com/
Once started, projects can be accessed at the following address:
http://localhost:3000/
1.2 Thin Projects
Next, simplify the project by removing files that are not used in the general project.
├ ─ / node_modules ├ ─ / public | ├ ─ the favicon. Ico | ├ ─ index. The HTML - | ├ ─ logo192. PNG - | ├ ─ logo512. PNG | ├ ─ mainfest. Json - | └ ─ robots. TXT ├ ─ / SRC - | ├ ─ App. CSS | ├ ─ App. Js - | ├ ─ App. Test, js - | ├ ─ index. The CSS | ├ ─ but js - | ├ ─ logo. The SVG - | ├ ─ reportWebVitals. Js - | └ ─ setupTests. Js ├ ─. Gitignore ├ ─ package. The json ├ ─ README. Md └ ─ yarn. The lockCopy the code
The directory structure is now much cleaner:
├ ─ / node_modules ├ ─ / public | ├ ─ the favicon. Ico | ├ ─ index. The HTML | └ ─ mainfest. Json ├ ─ / SRC | ├ ─ App. Js | └ ─ index. The js ├ ─ .gitignore ├─ Package. json ├─ READMECopy the code
An error message will be displayed after the above files are deleted. This is because the corresponding file reference no longer exists. You need to keep modifying the code to get the project up and running.
Modify the following files one by one:
SRC/App. Js:
function App() {
return <div className="App">React-CRX-v3</div>
}
export default App
Copy the code
SRC/index. Js:
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render(<App />, document.getElementById('root'))
Copy the code
Public/index. HTML:
<! DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>React App</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> </body> </html>Copy the code
The running effect is as follows:
2 Chrome Extension Basics
This tutorial is based on the latest Chrome Extension Manifest V3 and is the main reason for rewriting this tutorial again.
2.1 Overview of Manifest V3
Manifest V3 (MV3 for short) was released on November 9, 2020, many years after MV2. Chrome plugins using MV3 will provide better privacy, security and performance, as well as access to many new Web technologies. Details are as follows:
1. Privacy
The new plug-in can run without special permissions and then ask users for permission when it needs one.
2. The security
The access to external resources by plug-ins is restricted, and the introduction of external JS is prohibited. However, static external resources such as images and videos are not affected.
3. The performance
Make sure that plug-ins run well on a variety of devices, even if many plug-ins are installed.
Development of 4.
Lower development barriers, reduce development barriers, and develop plug-ins faster and better.
Ability to 5.
Continue to improve the ability of plug-ins, rich functions, give full play to greater value.
2.2 Main new features in Manifest V3
1.Service Workers replace background pages
With Service Workers, resources can be cached for offline access. Open Chrome :// Extensions/and you will see the Service Worker and background pages at the bottom of the MV3 plugin and MV2 plugin respectively.
2. Network request tuning a new declarativeNetRequestAPI allows plug-ins to modify and block network requests.
3. Remote resource access restrictions Prohibit access to external JavaScript and Wasm files. Images, audio and video files are not affected.
It’s good to promise, including async/await.
In addition, there are other changes. In the future, MV3 will introduce more new features.
For more information, please refer to the official website:
Developer.chrome.com/docs/extens…
2.3 Components of Chrome Extension
It mainly consists of the following parts:
- Manifest.json (plug-in configuration file)
- Popup (click the plug-in icon to popup the page)
- Content script (JS inserted into the target page for execution)
- Background script (a program running in Chrome background Service Workers)
【 manifest. Json 】
Manifest.json must be placed in the plug-in project root directory, which contains various configuration information for the plug-in, including popup, Content Script, background Script, and so on.
“Popup”
As a separate pop-up page, with its own HTML, CSS, JS, can be developed as a regular project.
“The content script”
Content Script is a JAVASCRIPT script that is injected into the target page and executed. You can retrieve the Dom of the target page and modify it. However, content Script’s JavaScript is isolated from the target page. That is, the Content script and the target page’s JavaScript do not pollute each other and cannot call each other’s methods.
Note that the above is only the isolation of the JS scope. DOM added to the target page via Content Script is the CSS that can be applied to the target page, resulting in CSS contamination.
The background script 】
Background script is permanently running in the browser background Service Workers without actual pages. This is where you put global code that needs to be run all the time. Importantly, Background Script has very high permissions and can make cross-domain requests in addition to calling almost any Chrome Extension API.
2.4 Planning the Directory structure generated by Build
After you understand the basics of Chrome Extension, you need to build the final directory as per the official Chrome Extension development document and manifest.json.
├─ favicon.ico <-- Popup ├─ insert.js <-- Insert javascript into target page (optional, Depending on the needs of the business) ├ ─ the manifest. Json < -- plug-in configuration file └ ─ / static ├ ─ / CSS | ├ ─ content. CSS < -- the content page style (with the target page pollution each other) | └ ─ main. CSS < - the popup page style (not pollution each other with the target page) ├ ─ / js | ├ ─ background. Js < - background script | ├ ─ content. js < -- the content script | └ ─ main. Js <--popup script ├ ─ /media <--popup script ├ ─ / pressCopy the code
The next step is to build such a directory structure.
2.5 configure the manifest. Json
Before developing Chrome Extension, you need to configure manifest.json.
Modify public/manifest.json (please remove the comment code) :
{"name": "Chrome V3", "version": "1.0", "description": "React Chrome V3 Demo." , // The MV3 "manifest_version": 3, // The root directory is the plugin package directory generated by the final build. "background": {"service_worker": "static/js/background.js"}, // content script "content_scripts": Matches "matches": ["<all_urls>"], // Inject the CSS of the target page, don't pollute the style "CSS" of the target page: ["static/ CSS /content.css"], // inject into the target page js, which is run in a sandbox, isolated from the target page, no pollution problems. Document_start, document_end, document_IDLE (default) "run_at": "Document_end"}], // Apply for chrome Extension API permissions: ["storage","declarativeContent"], // The external request address involved in the plug-in is not found. "Host_permissions ":[]; // If you want to insert images or js into the target page, you need to authorize the plugin local resources (the following is only an example). "web_accessible_resources": [ { "resources": [ "/images/app.png" ], "matches": ["<all_urls>"] }, { "resources": [" insert. Js] ", "matches" : [" < all_urls > "]}], / / popup page configuration "action" : "Default_popup ": "index.html", // Browser plugin button icon" default_icon": {"16": "/images/app.png", "32": "/images/app.png", "48": "/images/app.png", "128": "/images/app.png"}, // the browser plugin button hover display text "default_title": "React CRX MV3"}, // the plugin icon, if it is easy to use, all sizes also use a "ICONS ": { "16": "/images/app.png", "32": "/images/app.png", "48": "/images/app.png", "128": "/images/app.png" } }Copy the code
Manifest has many more configuration items, which can be found on the manifest website:
The manifest:
Developer.chrome.com/docs/extens…
Manifest_version:
Developer.chrome.com/docs/extens…
The content script:
Developer.chrome.com/docs/extens…
Permissions:
Developer.chrome.com/docs/extens…
🌷🌷—— 🌷🌷 end
If you are interested in this sharing, please follow my wechat official account “Sleeping plum and smelling Flowers” to continue reading the full version:
React+Antd 插件 图 片
React+Antd 插件 图 片
🎈 Wonderful follow-up chapters
3. Development structure design and build configuration
3.1 Development architecture design
3.2 configuration webpack
3.2.1 exposed webpack
3.2.2 support Sass/Scss
3.2.3 support Less
3.2.4 support Stylus
3.2.5 Setting a Path Alias
3.2.6 Forbid build projects to generate Map files
3.2.7 Setting multiple Entrances
3.2.8 Fixed the file name generated by build
3.2.9 Setting PopUp to import only its own index.js
3.2.10 Initializing the Project Architecture File
4. Introduce Ant Design
4.1 Installing Ant Design
4.2 Load on demand
4.3 Custom Antd Theme Color (optional)
5 Popup development
5.1 install the react – the router – the dom
5.2 Page Construction
5.2.1 PopUP entry file code
5.2.2 PopUP total route page code
5.2.3 PopUP global style code
5.2.4 PopUp Login page code
5.2.5 Popup Home page code
5.3 Viewing the POPUp Effect
6 Build the project and load the plug-in
7 Background script development
7.1 Setting popUp Rules
7.2 Why does the Plug-in icon not turn gray on the Disabled page
8 Content Script development
8.1 Inject floating balls into the target page
8.2 Develop Content Script using Ant Design
8.3 Viewing the Content Component Effect
8.4 Loading the Plug-in’s own Static Image Resources (Optional)
Resolve Ant Design style contamination of target pages
9.1 Remove antD global reset style
9.2 Content introduces the pull away ANTD – DIY style
9.3 Separate references to Ant Design component JS and CSS
10 Debug content Script in the development environment
11 API request
11.1 Background Pages Does not Support XMLHttpRequest (AxiOS)
11.2 Mock requests with mock.js and mockjs-fetch (optional)
11.3 Setting a Reverse Proxy Request in the Development Environment
11.4 Encapsulating APIS and FETCH service logic
11.5 Cancel mock.js to simulate requests
11.6 Delegate background Script to complete API requests
11.7 Implementing API requests for POPUp pages
11.8 Implement API requests for Content Script
11.9 Summary of key knowledge points
12 Other Instructions
12.1 Permission Permission configuration
12.2 Inserting the JS file of the Target Page
12.3 Service Worker Debugging
12.4 Debugging the POPUp Page
12.5 Simplifying the Final Build File
12.6 This tutorial code GitHub address
13 conclusion
If you are interested in this sharing, please follow my wechat official account “Sleeping plum and smelling Flowers” to continue reading the full version:
React+Antd 插件 图 片
React+Antd 插件 图 片