I wrote about chrome extensions a long time ago. Clear page ads? As a front-end, make a simple Chrome extension yourself.
This article focuses on sharing some of the most important knowledge and difficulties in the process of making extensions.
What is a Chrome extension
Extensions are small programs that modify or enhance Chrome. One of the biggest advantages for front-end engineers is that we can use familiar HTML, CSS, Javascript and other technologies to create extensions.
These ICONS are chrome extensions provided by various developers, as shown below:
Distinguish between extensions and plug-ins
Many people mistakenly call extensions plug-ins, so it’s important to distinguish between them.
“Extensions” and “plug-ins” are both forms of software components, and Chrome just gives the two types of components their own names, one called “extensions” and the other called “plug-ins”.
- Extension
Chrome is a component that extends the functionality of the browser by calling the Chrome API provided by Chrome, working at the browser level, using HTML + Javascript language development. Take the famous Adblock Plus.
- Plug-ins
A component that extends kernel functionality by calling the Webkit kernel NPAPI. It works at the kernel level and can theoretically be developed in any language that generates native binaries, such as C/C++, Delphi, etc. Flash Player plug-ins, for example, fall into this category. Plugins render parts of a web page declared with an
Develop your own extensions
OK, now that we have a brief understanding of what an extension is, let’s look at how to develop one.
Of course, first we need to figure out why we need an extension, and what does it do?
In my case, I recently developed a simple extension called URLHelper. You can download it from the Chrome App Store:
It was developed because, in our business development, the development process is often faced with an extremely long URL with N more parameters, which might look like this:
?
1 | http://tv.video.qq.com/xxx/xxx/xxx/index?rootdomain=test.tv.video.qq.com&guid=066de07bdd33422f95b7ddaf993b2004&tvid=0930 DCE900E081E142ED006B56025BA7 & appver = 3.1.0 & bid = 31001 & 101161688 & vipbid appid = = 38 & fromvipbid = 38 & cid = qk97pyegxz8kdug & vid = & pid = & mid = & the from = 501 & qua_info = PT % 3 dsnmapp % 26 chid % 3 d10009%26.vn % 3 d3. 1.0% % 26 pr 3 dvideo % 26 tvkplatform % 3 d670603%26 smarket % 3 d & type = 0 &listid=&matchid=&channelid=&source1=747&source2=709&penid=D21D81E4489E43422F842235B52DD&access=82E8E64DDD4A531B6FFA3E09 67F76&kt_login=qq&vuserid=&vusession=&oauth_consumer_key=101161688&kt_userid=924400965&kt_license_account=SNM_0059858531 &main_login=qq&kt_login_support=qq%2Cwx%2Cph&kt_boss_channel=tx_snm&ott_flag=2&sop=9&actid=&tvactid=&tv_params=policy_id %3D88&disable_update=&dp=&du=&viewid=&dv=&pageid=&ptag=&redirect_url=http%3A%2F%2Ftest.tv.video.qq.com%2Fktweb%2Fpay%2Fp hone%2Fscan%3Frootdomain%3Dtest.tv.video.qq.com%26guid%3D066de07bdd33422f95b7ddaf993b2004%26tvid%3D0930DCE900E081E142ED0 06 b56025ba7%26 appver % 3 d3. 1.0% 26 bid % 3 d31001%26 appid % 3 d101161688%26 vipbid % 3 d38%26 fromvipbid % 3 d38%26 cid % 3 dqk97pyegxz8kdug % 2 6 vid % 3 d % 26 pid % 3 d % 26 mid % % 26 from 3 d % 3 d501%26 qua_info % 3 DPT 253 2526 chid dsnmapp % % % 253 2526.vn d10009% % 253 d3. 1.0% 2526 pr 253 dvideo % % 2 526TVKPlatform%253D670603%2526SMARKET%253D%26type%3D0%26listid%3D%26matchid%3D%26channelid%3D%26source1%3D747%26source2% 3D709%26openid%3DD21D81E44801E9E43422F842235B52DD%26access_token%3D82E8E64DDD4EDA531B6FFA3E09676F76%26kt_login%3Dqq%26vu serid%3D%26vusession%3D%26oauth_consumer_key%3D101161688%26kt_userid%3D924400965%26kt_license_account%3DSNM_0059858531%2 6main_login%3Dqq%26kt_login_support%3Dqq%252Cwx%252Cph%26kt_boss_channel%3Dtx_snm%26ott_flag%3D2%26sop%3D9%26actid%3D%26 tvactid%3D%26tv_params%3Dpolicy_id%253D88%26disable_update%3D%26dp%3D%26du%3D%26viewid%3D%26dv%3D%26pageid%3D%26ptag%3D% 26opres%3D0&%24from=201 |
No kidding, it’s probably longer than that.
For debugging purposes, it is often necessary to find a particular parameter and get or modify its value.
You can try it, post it to your browser, find the CID parameter, and change it to a different value. Without tools, the process can be painful. Once is fine, but if you do it dozens of times a day, it’s worth considering tools.
With this in mind, I created an extension called URLHelper, whose interface looks like this. It is very convenient to delete, check, change, sort URL parameters, and refresh the page by modifying parameters:
Therefore, I think each front-end can be developed to solve the various problems we encounter in working life when using the browser, such as the famous:
- WEB front-end assistant provides string encoding, JSON formatting
- PageSpeed provides page performance detection and so on
- The QR code generator converts the URL into the corresponding QR code
Extension program architecture
OK, let’s talk a little bit about extension development.
For documentation on extensions, check out these articles:
- Create a Chrome extension
- Extended development documentation
First, I think it’s important to understand the basic architecture of the entire extension. There are several very important files:
Content scripts — Content scripts
Content scripts are javascript scripts that can run inside pages that have already been loaded by the browser. You can think of Content Script as part of a web page, not as part of the extension it’s in.
Some examples of its functions and application scenarios are as follows:
- Find unlinked urls on your web page and turn them into hyperlinks
- Find specific information or DOM structures and increase font sizes to make text more readable
- Discover and process microformatted data in the DOM
We can think of it this way: after the page is loaded, our extension will inject the page with one or more scripts that get the details of the Web page that the browser is visiting. That is, we can use this script to collect all the information we need on the page.
Take my URLHelper example above. In this extension, the Content script takes the URL of the page and passes it to the extension’s background or popUp page.
Of course, if you only need a script to fetch information about a page every time you inject it and report it to your own server, this extension will only need one Content scripts. It doesn’t need to interact with other interfaces or scripts, so what the extension does for you is automatically inject the script and you need to do it manually every time.
Popup — Popover page
The popup page is also pretty easy to understand. In manifest.json it is browser_action, which is the interface for our extension (popup), as shown in the screenshot above:
This interface is actually a Web page, click any extension page, right click, you can see the check option pop up, click this option, will pop up a developer tool, we can happily start the page to view DOM structure, check network status, Debug and other operations:
And then:
The point is that the popup page is completely under our control, just like a normal Web page, and we can use Chrome’s messaging mechanism to interact with Content Scripts, which gives us some control over the page.
Take my URLHelper extension as an example. In this extension, when I click the refresh button in the extension interface, IT takes the modified parameters out of the DOM of the extension interface and passes them to Content Scripts through Chrome’s messaging mechanism. Then Content Scripts takes the new parameter and assigns it to the document.location.href of the current browser window page to refresh the page.
Background – Background page
In addition to the Popup page, there is also a background page.
The Chrome extension divides background pages into two types:
- A background web page that runs continuously
- The event page
Persistence is the fundamental difference between event pages and background pages. (It can be understood as a thing when first used)
Applications and extensions often require long-running scripts to manage some task or state, which is where background pages come in. Event pages are loaded only when needed and unloaded when they are inactive to free up memory and other system resources, so they are generally recommended.
It exists for the purpose of managing tasks or states over a long period of time throughout the life cycle of an extension. Its main functions and application scenarios are roughly as follows:
- Triggers an event that the event page listens for
- The first time an application or extension is installed or updated to a new version (to register events)
- Content scripts or other extensions send messages
- Extension of the other view invokes the runtime. GetBackgroundPage
Take my URLHelper as an example. In this extension, I use a background web page that runs continuously. When the browser refreshes the page and injects the Content Script for the first time, it gets the current page URL. It then sends a message with the URL information to the background page, which receives the message and forwards it to the PopUp page.
Extension program summary
In my opinion, the most important parts of an extension are the above three parts:
- Content scripts — Content scripts
- Popup — Popover page
- Background – Background page
We configure them with some additional information via a manifest.json manifest file. For more information about manifest.json, you can poke: manifest.
Next, our extensions will have the flexibility to perform various functions, and most importantly, to communicate with each other!
Passing information data between content scripts, pop-up pages, and event pages is the most important part of an extension.
Message passing for extensions
Messaging is necessary because content scripts run in the context of a Web page rather than an extender, so they usually need some way to communicate with the rest of the extender.
Communication between extensions (popup pages and background pages) and content scripts uses messaging. Both sides can listen for messages from the other side and respond through the same channel. The message can contain any valid JSON object.
Using chrome. * apis
Message passing, mainly using the Chrome browser’s built-in Chrome object. Open your browser and try it out. Chrome objects actually contain a lot of functionality:
All types of messaging are done through this Chrome object, divided into:
- Simple one-time request
- Long time connection
- Cross-extender messaging
- Send messages from web pages
- Native message communication
Of course, a simple one-time request would suffice for a normal extender, just to give you two examples.
Suppose our manifest.json is simply defined as follows:
?
12 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | # manifest.json { "name" : "Url Helper" . "version" : "1.0.0" . "author" : "Coco" . "manifest_version" : 2. "browser_action" : { "default_popup" : "popup.html" }, "background" : { "scripts" : [ "background.js" ] }, "content_scripts" : [ { "js" : [ "contentScript.js" ] } ] } |
Pass messages from the Content Script to the background event page
- Content Script is a Script that is injected into a page
?
12 3 4 5 6 7 8 9 10 11 12 13 14 | # contentScript.js // Send a message chrome.runtime.sendMessage( { msg: 'Send messages from Content Script to event page' . result: 1 }, function (response) { if (response && response.msg) { console.log(response.msg); } } ); |
- Background page
?
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 | #background.js // Receive the message chrome.runtime.onMessage.addListener( function (request, sender, sendResponse) { if (request.result) { sendResponse({ farewell: "ok" }); } }); |
On the sending side, we can use either the Runtime. sendMessage or tabs. SendMessage methods. These methods allow you to send JSON serializable messages from a content script to an extender or vice versa, respectively, and the optional callback argument allows you to process the response from the other side if needed.
On the receiving end, we need to set up a Runtime. onMessage event listener to handle the message.
Pass messages to Content Script from the Popup page
Here’s another example of flipping a message from a popup page to Content Script.
- Popup page
?
12 3 4 5 6 7 8 9 10 11 12 13 | # popup.html page to introduce popup.js let obj = { msg: 'Send a message from the Popup page to the Content Script' . result: 0 }; // Send a message chrome.tabs.query({ active: true , currentWindow: true }, function (tabs) { chrome.tabs.sendMessage(tabs[0].id, obj, function (response) { console.log( "Send Success" ); }); }); |
- Content Script
?
1, 2, 3, 4, 5, 6, 7, 8, 9, 10 | # contentScript.js // Receive the message chrome.runtime.onMessage.addListener( function (request, sender, sendResponse) { console.log(sender.tab ? "From content script:" + sender.tab.url : "From the extender" ); if (request && ! request.result) { console.log(result.msg); } }); |
One thing to note here is that when passing a message from a popup page to Content Script, the browser may have multiple tabs open at the same time, so you need to specify which page to pass to and which TAB to send it to.
Use Chrome.tabs. Query ({active: true, currentWindow: true}, function(tabs) {}) to correctly select the currently open TAB.
For more information about message passing, you can click here: message passing.
Package the extension and release it to the Chrome App Store
The extension has been developed and is expected to be downloaded by others. Then of course you need to publish to the app store. The process is roughly as follows:
Log in to the Chrome Developer Information Center.
First, you need to have a Google account, click here, and log in to the online app store.
Add a new entry and upload the file as a ZIP file.
After success, you will log in to this screen:
In this screen we can choose to add new content:
Make sure you pack it*.zip
Format, and have the most important in the root directorymanifest.json
Files, like the entire directory structure I uploaded, are very simple:
For the first time, it costs $5
Once the file has been selected and successfully uploaded, the next step is very important. Google charges a developer registration fee of $5 for the first release of an extension, and up to 20 extensions can be released later.
It seems that bank cards in Mainland China are not acceptable for payment here, so you can only choose foreign savings cards and credit cards such as VISA for payment, and you can choose the United States as your region.
The payment is complete and you are ready to release happily
OK, finally the payment is completed, we can release smoothly, wait for a moment, you can search to develop our own extension program!
Afterword.
Developing a Chrome extension isn’t hard, and it’s a lot of fun. Those who are interested but afraid of trouble can refer to my small project to change. Github — URL Helper
Well, the end of this article, I hope to help you 🙂
If there are any questions or suggestions, you can exchange more original articles, writing is limited, talent and learning is shallow, if there is something wrong in the article, hope to inform.
(^_^) a tip and a coffee (^_^)