I. Introduction
When it comes to Chrome Extension, everyone’s browser has several plug-ins installed more or less, such as one-click translation, ad blocking, screen recording, etc. By using these plug-ins, we can effectively improve our Work efficiency; but sometimes, there is no ready-made plug-in on the market for a certain function we want. As a developer, it is natural to think whether you can develop a customized plug-in by yourself? There are many good tutorials on the development of Chrome plug-ins on the Internet, which can help us quickly develop a plug-in. This article changes the way of thinking, starting from the application, by explaining the characteristics of the plug-in to inspire readers which scenarios can be solved by the plug-in at work.
This article focuses not on the basic development of the Chrome plug-in, but on the principles and applications. It will start with some important features of the plug-in and combine the actual plug-in cases to analyze the role of these features, so as to inspire readers to develop using these features Your own efficiency tool, create your own handy weapon.
Second, what is a Chrome extension
What is a Chrome extension? In our impression, it is like an application running in a browser. Think of the browser as a mobile phone. The plug-in is like an application. We download it from the Chrome App Store and install it in the Chrome browser. Run it in the browser.
Let's take a look at the official explanation:
Chrome Extension is a small software program that can be used to define the browsing experience of the browser, allowing users to customize the functions and behaviors of the Chrome browser according to personal needs or preferences. The main technology stacks used are HTML, Javascript, and CSS.
One sentence summary: The Chrome extension plug-in uses the front-end technology stack to customize the browser’s functions and improve the user experience .
You may have heard a word: Chrome Plugin. The translation is a Chrome plug-in, which is very similar to the Chrome extension plug-in. It is especially easy to confuse, so what is the difference between them?
- Chrome Extension only used to enhance the functions of the browser webpage. It uses the existing functions provided by the browser and various APIs to combine functions to improve the browser experience and stay at the browser level;
- Chrome Plugin can not only enhance the functions of web pages, but also extend the functions of the browser itself; when the functions provided by the browser can no longer meet your needs, you need to extend the functions of the browser through a compiled language such as C/C++ For example, our commonly used Flash plug-in, Chrome Plugin works at the kernel level.
Three, Chrome extension plug-in composition and core mechanism
3.1 The composition of the Chrome extension
A Chrome extension plug-in usually consists of 3 types of files:
1) The configuration file manifest.json is used to configure the extension's name, version number, author, icon icon, pop-up interface, permissions, script path and other information;
2) Resource files such as pictures and css;
3) js script file, which contains:
- popup.js : used with popup.html to display the page and page logic control when clicking the plug-in icon;
- background.js : used to define a background page, which is equivalent to a resident page with the same life cycle as the browser;
- content_scripts.js : Used to inject JS scripts into the page, it can operate the page dom, but will not conflict with the script in the page.
3.2 The core mechanism of Chrome extension
There are several core concepts in Chrome extensions: Extension Page, background.js, Content_script.js. When are they triggered, what role do they play, and how do they communicate with each other? You can look at the following diagram:
As can be seen from the figure, there are three processes: extension process (Extension Process), page rendering process (Render Process), browser process (Browser Process).
1) Run Extension Page in the extension process, Extension Page mainly includes backgrount.html and popup.html:
- There is no content in backgrount.html. It is created by background.js. When the browser is opened, it will automatically load the background.js file of the plug-in. It is independent of the web page and always runs in the background. It is mainly provided by calling the browser API and browser to interact;
- popup.html is different. It has content and is a real page. Like our ordinary web page, it is composed of html, css, and Javascript. It is loaded on demand and requires the user to click the button in the address bar. Only when triggered can the page pop up.
2) The rendering process mainly runs the Web Page. When the page is opened, content_script.js will be loaded and injected into the environment of the web page. It is the same as the Javascript introduced in the web page. It can operate the DOM Tree of the web page and change the display of the page. Effect;
3) The browser process is more of a bridge here, as a relay can realize the message communication between Extension Page and Content_script.js.
What can Chrome extensions do?
The usage direction of Chrome extensions mainly includes two parts:
Change the appearance of the browser:
- brower Actions
- page Actions
- content menus
- Desktop notification
- Omnibox
- override alternative page
interact with the browser :
- Cookie control
- Label control
- Bookmark control
- Download control
- Event monitoring
- Network request
- acting...
Below we use examples to analyze the use cases of these functions:
Example 1: Replace page
Using alternative pages, you can replace some of the default specific pages of Chrome and use the pages provided by the extension instead. This allows developers to develop more interesting or useful basic function pages.
"chrome_url_overrides": {
"newtab": "newTab.html", //替换新标签页
"bookmarks":"bookmarks.html", //替换书签管理器页面
"history":"history.html" //替换历史记录页面
},
The following is a rendering of replacing the new tab page:
Example 2: Cookie control
Through the Cookie API, you can add, delete, modify, and check the browser's cookies. For example, in our development work, we often need to clear the browser cache frequently. Every time we need to find the clear button, pop up a dialog box, and confirm, the operation is very cumbersome. If we develop a chrome extension plug-in, we can easily achieve one-click shortcuts. To clear your browser’s cookies and other caches, you can refer to the Clear Store plug-in.
Example 3: Tag control
Use the chrome.tabs API to interact with the browser's tab system, you can query, create, modify and rearrange the tabs in the browser; when we use the browser, we often open many tabs, which is very confusing. When looking for a certain page to open, it is inefficient and painful. It would be great if these tabs can be organized and displayed in an orderly manner. Here is a Chrome extension plug-in for everyone: OneTab, this plug-in will all open tabs Arrange them in an orderly manner on the new page, as shown in the figure below, which is clear at a glance.
We can even realize the interaction between tabs through tabs. For security reasons, there is no document in the tab attribute, so the dom element in a certain tab page cannot be directly obtained in the extension, but it can be achieved by sending an event request:
chrome.tabs.sendRequest(tab_id, {
hello: "ok"
}, function(response){
// response处理
});
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (request.hello == "ok"){
sendResponse({
data: $("#hello") // 获取id是hello的元素发过去
});
}
}
);
Example 4: Intercept request or reverse proxy
In the page performance check, we often check whether the page image resource is too large, such as 200K, to obtain an image list page that is too large.
The chrome.webRequest API can only be used in background.js, so it can be intercepted by images, and the link can be sent to the content\_script.js of the current page through a message, and then the image can be downloaded and size checked in content\_script.js.
// background.js
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
// url就是图片下载的链接
const { url ,tabId} = details
// 向content_script.js发送下载图片链接
chrome.tabs.sendMessage(tabId, {picUrl: url}, function(response) {
//...
});
return {cancel: isCancel};
},
{urls: ["http://baidu.com"],types: "image"},
["blocking"]
);
// content_script.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse)
{
if(sender.tab && request.picUrl && request.picUrl == sender.tab.id){
//获取图片大小并下载
}
});
Example 5: Page element operation
Use Content_script.js to manipulate dom elements, perform operations on page elements, realize automatic login, and free your hands.
//输入
function input(inputElement, content) {
let event = document.createEvent('HTMLEvents');
event.initEvent('input', true, true);
inputElement.value = content;
inputElement.dispatchEvent(event)
}
const usernameDom = document.getElementById("userName"); //用户名
const pwdDom = document.getElementById("password"); //密码
const btnDom = document.getElementById("submitBtn");//按钮
//输入后,点击确认
input(usernameDom, "姓名");
input(pwdDom, "密码");
//登录
btnDom.click();
Five, business practice
Pain Points : I am currently mainly responsible for the business of the vivo global mall. Globalized businesses will face the problem of international language. We independently developed a multi-language management backend, configured key-value, and the front-end obtains multi-language through the interface to display on the page ; If you view the page and feel that a certain copy is not suitable, you need to perform a series of operations as shown in the figure below if you want to modify it:
It can be seen that when the operator wants to modify the copy, he first needs to know the key value corresponding to the copy, and the key value cannot be obtained on the page, it needs to be provided by the developer, and then it needs to update the value of the corresponding key on the multilingual management platform.
This encounters two problems:
- You cannot see what you get, and you cannot know the key value when you see the page;
- What you see cannot be modified directly, you need to go to another management platform to modify;
At present, this can still be operated when there are few modifications. When there are many modifications, this operation is very cumbersome and inefficient.
thinking:
1) Can the operation be modified directly on the page and take effect?
2) If it can be modified, how to implement cross-domain requests?
3) How to realize login authorization?
If you are familiar with Chrome extensions, you will find that Chrome is tailored for this and can perfectly solve these problems.
implementation scheme:
1) Modify the dom involved in the copy on the page, and bind the multi-language key value.
<div data-lang-key="address.delete.button">{{ language.addressDeleteButton }}</div>
2) Use Content_script, js to operate the page dom element. When the plug-in is started, the contenteditable attribute is added to the dom of all the modifiable copy of the page to support editability, as shown in the figure;
3) Create a modification panel to get the currently selected key value and value value, and the modified value, as shown in the figure above, the upper right panel.
4) Use the Chrome plug-in feature to support cross-site requests, and send modification requests directly to the multi-language platform.
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
try{
sendResponse(JSON.parse(xhr.response));
}catch(e) {
// 异常处理
}
}
};
xhr.send(new URLSearchParams(params));
return true
}
);
5) The Chrome plug-in can be used to obtain the Cookie feature in the browser, open a new tab to open the multi-language background, and log in. After the login is successful, the requested authorization can be modified.
Six, summary
In conclusion, I often sigh in life: I have seen a lot of life principles, but I still have a bad life. Similarly, I have used a lot of Chrome plug-ins, but the code is still not good for one of their own plug-ins, so I will finally give you a plug-in to read the source code of the Chrome plug-in. It can be called the plug-in in the plug-in, the king of the plug-in- Chrome extension source viewer. can easily view the source code of other plug-ins through it, so that we can stand on the shoulders of giants and move forward~~
Author: vivo Internet front-end team-Zhang hao
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。