当前位置:网站首页>Chrome plug-in features and case analysis of actual combat scenarios
Chrome plug-in features and case analysis of actual combat scenarios
2022-06-23 23:45:00 【2020labs assistant】
One 、 Preface
mention Chrome Extension plug-in (Chrome Extension), Everyone has more or less several plug-ins installed in their browser , Like one click translation 、 Advertising screening 、 Video recording and so on , By using these plug-ins , Can effectively improve our work efficiency ; But sometimes , There is no ready-made plug-in on the market for a function we want , As a developer, I naturally think of , Whether you can develop a customized plug-in by yourself ? There are a lot of good online about Chrome Plug in development tutorial , It can help us quickly start developing a plug-in , Let's change our thinking , Start with applications , Explain the characteristics of plug-ins to inspire readers what scenarios can be solved through plug-ins .
The focus of this article is not Chrome Basic development of plug-ins , But focus on principles and Applications , I'll start with some important features of plug-ins , Combined with the actual plug-in case , To analyze the role of these characteristics , This can inspire readers to use these features to develop their own efficiency tools , Create your own sharp weapon .
Two 、 What is? Chrome Extension plug-in
What is? Chrome Extension plug-in ? In our impression , It's like running an application in a browser , You can think of a browser as a mobile phone , So plug-ins are like applications , We from Chrome Download from the app store , And then install it to Chrome Browser , You can run it in the browser .
Let's look at the official explanation :
Chrome Extension It's a small software program , It can be used to define the browser's browsing experience , So that users can customize according to their personal needs or preferences Chrome Browser functions and behavior , The main technology stack used is HTML、Javascript and CSS.
One sentence summary :Chrome The extension uses the front-end technology stack , To customize the functions of the browser , Improve user experience .
Maybe you've heard another word :Chrome Plugin. Which translates to Chrome plug-in unit , and Chrome Extensions are very similar , It's particularly confusing , So what's the difference between them ?
- Chrome Extension Just to enhance the functionality of the web browser , It uses the existing functions and various functions provided by the browser API, Function combination , To improve the browser experience , Stay at the browser level ;
- Chrome Plugin It can not only enhance the function of web pages , At the same time, it can expand the functions of the browser itself ; When the functions provided by the browser can no longer meet your needs , You need to pass C/C++ Such a compilation language to expand the functions of the browser , For example, we often use Flash plug-in unit ,Chrome Plugin Working at the kernel level .
3、 ... and 、Chrome Composition and core mechanism of extension plug-ins
3.1 Chrome The composition of the extension
One Chrome Extensions are usually made up of 3 Class files consist of :
1) The configuration file manifest.json, The name used to configure the extension 、 Version number 、 author 、 Icon icon、 Pop up screen 、 jurisdiction 、 Script path and other information ;
2) picture 、css Etc ;
3)js Script files , It includes :
- popup.js: For collocation popup.html Use , Click the plug-in icon to display the page and page logic control ;
- background.js: Used to define a background page , Equivalent to a resident page , The lifecycle is consistent with the browser ;
- content_scripts.js: Used to inject... Into the page JS Script , It can manipulate pages dom, But it doesn't conflict with the script in the page .
3.2 Chrome The core mechanism of the extension
Chrome Several core concepts in the extension :Extension Page、background.js、Content_script.js , When do they trigger , What's the role , How to communicate with each other ? Take a look at the diagram below :
As you can see from the diagram , There are three processes : Extension process (Extension Process)、 Page rendering process (Render Process)、 Browser process (Browser Process).
1) Run in the extension process Extension Page,Extension Page It mainly includes backgrount.html and popup.html:
- backgrount.html There's nothing in it , It's through background.js Create build , When the browser opens , The plug-in will be loaded automatically background.js file , It is independent of web pages and always runs in the background , It mainly calls the... Provided by the browser API Interact with the browser ;
- popup.html Is different , It has content , It's a real page , And our ordinary web The page is the same , from html、css、Javascript form , It is loaded on demand , The user needs to click the button in the address bar to trigger , To pop up the page .
2) The rendering process mainly runs Web Page, When opening a page , Will content_script.js Load and inject into the environment of the web page , It is similar to the Javascript equally , You can operate the DOM Tree, Change the display effect of the page ;
3) The browser process plays a more bridge role here , As a transit, you can Extension Page and Content_script.js Message communication between .
Four 、Chrome What extensions can do
Chrome The use direction of the extension mainly includes two parts :
Change the appearance of the browser :
- brower Actions
- page Actions
- content menus
- Desktop notification
- Omnibox
- override Substitute page
Interact with the browser :
- Cookie control
- The label control
- Bookmark control
- Download control
- Event monitoring
- Network request
- agent ...
Let's analyze the use cases of these functions through examples :
example 1: Replace page
Use alternate pages , Can be Chrome Some specific default pages are replaced , Instead, use the page provided by the extension . This allows developers to develop more interesting or practical basic function pages .
"chrome_url_overrides": {
"newtab": "newTab.html", // Replace new tab
"bookmarks":"bookmarks.html", // Replace bookmark manager page
"history":"history.html" // Replace History page
},The following is a rendering of replacing the new tab :
example 2:Cookie control
adopt Cookie Of API, You can make changes to the browser Cookie Add, delete, modify and check . For example, in our development work , It is often necessary to clear the browser cache frequently , Each time you need to find the clear button , Pop-up dialog box , Confirm , The operation is very complicated , If you develop a chrome Extension plug-in , You can easily clear the browser with one click Cookie Equal cache , You can refer to Clear Store plug-in unit .
example 3: The label control
Use chrome.tabs API Interact with the browser's tag system , You can query , establish 、 Modify and rearrange the tabs in the browser ; When we use the browser , Often open a lot of tabs , It looks chaotic , When you want to find an open page halfway , Inefficient and painful , If only these tabs could be organized and displayed orderly , Here's a recommendation for you Chrome Extension plug-in :OneTab, The plug-in arranges all open tabs in order in the new page , Here's the picture , Be clear at a glance .
We can even go through tabs Realize the interaction between tabs , For safety reasons ,tab There are no attributes in document, Therefore, it is not possible to directly obtain... In a label page in the extension dom Elements , But you can do this by sending event requests :
chrome.tabs.sendRequest(tab_id, {
hello: "ok"
}, function(response){
// response Handle
});chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (request.hello == "ok"){
sendResponse({
data: $("#hello") // obtain id yes hello Send the element of
});
}
}
);example 4: Intercept requests or reverse proxies
During page performance spot check , We often check whether the page image resources are too large , for example 200K, Get a picture list page that is too large .
chrome.webRequest API Only in background.js Use in , So it can be intercepted by pictures , Pass the link to the of the current page through a message content_script.js, And then in content_script.js Image download and size check in .
// background.js
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
// url Is the link to download pictures
const { url ,tabId} = details
// towards content_script.js Send a link to download pictures
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){
// Get the picture size and download
}
});example 5: Page element operation
utilize Content_script.js operational dom Elements , Operate on page elements , Realize automatic login , Liberating hands .
// Input
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"); // user name
const pwdDom = document.getElementById("password"); // password
const btnDom = document.getElementById("submitBtn");// Button
// After input , Click on the confirmation
input(usernameDom, " full name ");
input(pwdDom, " password ");
// Sign in
btnDom.click();5、 ... and 、 Business practice
Pain points : I am mainly responsible for vivo The business of global mall , Global businesses will face the problem of international language , We have independently developed a multilingual management background , To configure key-value, The front end obtains multi language information through the interface and displays it on the page ; If the operation view page , I don't think a copy is suitable , Want to modify , You need to perform a series of operations as shown in the figure below :
You can see that when the operator wants to modify the copy , He first needs to know what the copy corresponds to key value , And you can't get... On the page key value , Need to let developers provide , Then you need to update the corresponding language on the multilingual management platform key Value .
There are two problems :
- What you see is what you get , You can't know when you see the page key value ;
- What you see cannot be directly modified , You need to go to another management platform to modify ;
At present, with few modifications , It can still be operated , When there are a lot of changes , This operation is cumbersome , Efficiency is very low .
reflection :
1) Whether the operation can be modified directly on the page and take effect ?2) If you can modify , How to implement cross domain requests ?3) How to realize login Authorization ?
If the Chrome Extensions are familiar with , Will find Chrome It's tailor-made for this , Can solve these problems perfectly .
Implementation scheme :
1) For the copy involved in the page dom Make changes , Binding multiple languages key value .
<div data-lang-key="address.delete.button">{{ language.addressDeleteButton }}</div>2) utilize Content_script,js Can operate the page dom Elements , When starting the plug-in , Copy all modifiable documents on the page dom increase contenteditable attribute , Support editable , Pictured ;
3) Create a modification panel , Get the currently selected key Values and value value , And the modified value , Pictured above , Top right panel .
4) utilize Chrome The plug-in supports the feature of cross site requests , Send modification requests directly to multilingual platforms .
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) {
// exception handling
}
}
};
xhr.send(new URLSearchParams(params));
return true
}
);5) utilize Chrome The plug-in can get the information in the browser Cookie characteristic , Open a new tab to open the multilingual background , Log in , After successful login, the requested authorization modification can be realized .
6、 ... and 、 summary
So to conclude , I often sigh in my life : I've seen a lot of truth in life , Still have a bad life . Again , Used a lot Chrome plug-in unit , I still can't code my own plug-in , So finally, I'll give you a reading Chrome Plug in source code plug-in , It can be called the plug-in in the plug-in , The king in the plug-in ——Chrome extension source viewer. Through it, you can easily view the source code of other plug-ins , Let's stand on the shoulders of giants and move forward ~~
author :vivo Internet front end team -Zhang hao
边栏推荐
- NLog details
- Short video enters the hinterland of online music
- Autofac details
- Grpc security -2: fast implementation of server-side JWT authentication
- 在OpenCloudOS使用snap安装.NET 6
- 多门店药品进销存系统源码 大型连锁药店管理系统源码
- “山大地纬杯”第十二届山东省ICPC大学生程序设计竞赛
- 再见,2020,这碗毒鸡汤,我先干了
- 完整开源项目之诗词吧 APP
- Niuke.com: the double pointer problem of receiving rainwater
猜你喜欢

List中subList的add造成的死循环

MySQL索引底层为什么用B+树?看完这篇文章,轻松应对面试。
Several cases of index invalidation caused by MySQL

AutoCAD -- summarize three methods of drawing rounded corners in CAD

【Proteus仿真】T6963C驱动PG12864示例(带中英文显示)
![入参参数为Object,但传递过去却成了[object object] 是因为需要转为JSON格式](/img/8c/b1535e03900d71b075f73f80030064.png)
入参参数为Object,但传递过去却成了[object object] 是因为需要转为JSON格式

Analysis of Alibaba cloud Tianchi competition -- prediction of o2o coupon

完整开源项目之诗词吧 APP

Inftnews | where should the future of the creator economy go in the Web3 world?

微信录制视频转圈效果如何实现?
随机推荐
不同物体使用同一材质,有不同的表现
STM32-------定时器
Bitmap加载内存分析
Why do MySQL indexes use b+ trees at the bottom? After reading this article, you can easily handle the interview.
6、STM32——串口数据收发基础
6月25日PMP考试敏捷怎么考?替你分忧解难
laravel之任务队列
NLog details
To ensure the safety of groups with special difficulties, Guangzhou Civil Affairs made every effort to do a good job in the three prevention work
【HackTheBox】Fawn
AUTOCAD——总结CAD画圆角的三种方式
Le roman du drapeau de l'imitation haute version flutter, apprenez - le
Autofac详解
有哪些劵商推荐?在线开户安全么?
Construction of cache stack FIFO in different application scenarios for PLC data operation series (detailed algorithm explanation)
STM32-------外部中断
Some explanations of Tim timer of embedded interface and STM32 template library function of NVIC
A cartoon reading app highly imitating Tencent comics
smart-doc + Torna 兼容版本
Which securities dealers recommend? Is online account opening safe?