introduce

Browser plug-in is essentially the use of front-end HTML CSS javascript and other technologies, using the API provided by the browser, to achieve a variety of different functions

plug-ins

Let’s start by looking at the file composition of the plug-in we will be developing

Manifest.json: We must have a file named manifest.json at the root of the project. This file is the entry to the functionality of the plug-in and tells the browser about the basic information of the plug-in and the resource files that need to be loaded and executed.

  • Name The name of the plug-in
  • Version Plug-in version
  • Manifest_version Manifest version
  • Description Description of the plug-in (optional)
{
    "name": "hello extension"."description": "Base Level Extension"."version": "1.0"."manifest_version": 2,}Copy the code
  • In the ICONS management interface, which presents ICONS, different size options can be set for different scenarios
{
    "icons": {
        "16": "images/extension_icon16.png"."32": "images/extension_icon32.png"."48": "images/extension_icon48.png"."128": "images/extension_icon128.png"}},Copy the code
  • Background triggers the execution of the JS resources specified in the background option when an extender is enabled, and remains for the entire life of the extender until the extender is closed or deleted. Background is used for task and state control and management
The // scripts suboption specifies the path and filename of the JS file to execute
{
    "background": {
        "scripts": ["background.js"]."persistent": false}}Copy the code

Background. Js is usually used to monitor events in the outer most chrome. Runtime. OnInstalled. AddListener (() = > {}) to initialize the plug-in, monitor plugin after the installation is successful, will trigger the corresponding logic began to work

  • The permissions attribute is an array that applies for chrome API permissions, It can only be used if requested in this option (such as via XMLHttpRequest) Cross-domain requests for data, access browser tabs, get current active tabs, notifications, set plug-in activation rules, storage like localStorage, and so on )
{
    "permissions": [
        "http://xxx.com/api"
        "tabs"."activeTab"."notifications"."declarativeContent"."storage"],}Copy the code

There are two main functions to implement UI interaction with the user: Browser_action and page_action Choose one of them

  • Browser_action provides functionality for all sites, and the plugin icon is always active
    {
        "browser_action": {
          "default_popup": "popup.html"        // The page to display when you specify the click plug-in icon
          "default_icon": "images/icon.png".// Specify the icon of the plug-in to display in the browser toolbar
          "default_title": "display tooltip" // When the mouse hovers over the plugin image, the text displayed is called tooltip; If this configuration option is not available, the name option value in menifest. Json is displayed when suspended}}Copy the code
  • Page_action is only for the functions provided by the corresponding target website. The plugin will set the rules to activate the plugin in the background page. Only the plugins that meet the conditions are activated

    background scriptIn,chrome.runtime.onInstalled.addListener(()=>{})Used in initializationchrome.declarativeContentDefines the rules by which plug-ins are activated

    {
        "page_action": {"default_popup": "popup.html".// The page to display when you specify the click plug-in icon
            "default_icon": "hello_extension.png" // Specify the icon of the plug-in to display in the browser toolbar
            "default_title": "display tooltip"}},Copy the code
        chrome.runtime.onInstalled.addListener(function() {
        // Replace all rules ...
        chrome.declarativeContent.onPageChanged.removeRules(undefined.function() {
        // With a new rule ...
        chrome.declarativeContent.onPageChanged.addRules([
            {
            // That fires when a page's URL contains a 'g' ...
            conditions: [
                new chrome.declarativeContent.PageStateMatcher({
                pageUrl: { urlContains: 'g' }, // The plugin will only be activated if the content of the URL contains the letter G})].// And shows the extension's page action.
            actions: [ new chrome.declarativeContent.ShowPageAction() ]
            }
        ]);
        });
    });
    Copy the code

popup.html

Popup. HTML is the default popup option specified by browser_action or page_action. Popup is an HTML resource that is triggered by clicking on the plugin icon. It can contain links to stylesheets and script tags, but does not allow inline JavaScript.

Content Script injects extension code into the current Web page, that is, in the context of the current Web page, can access the page’s DOM information and modify the DOM, has access to the Chrome API, and can pass the information to the parent plug-in

  1. Content Script works in a separate space so that variables and functions defined in web pages or other Content Scripts are not accessed or called; the only thing they share is the DOM
  2. Content scripts communicate with Page actions or Browser actions by passing messages. The correct mechanism should be:
    • Js in Page action or Browser Actionchrome.tabs.sendMessage()Publish a request message passing the current TAB id and other information
    • Note: Publishing messages to Content Script from Page Action or Browser Action must be usedchrome.tabs.sendMessage()Publishing simple information from Content Script to Page action or Browser Action can be usedchrome.runtime.sendMessage()
     chrome.tabs.sendMessage(
         tabs[0].id, // Id of the active TAB page
         {greeting: "hello"}, // The information to be passed
         function(response) { // The callback function used to receive feedback
         console.log(response.farewell);
     });
    Copy the code
    • Content Script completes initialization and setupchrome.runtime.onMessage().addListener()Listen for events and wait for the other side to publish the request information
    chrome.runtime.onMessage.addListener(
     function(request, sender, sendResponse) {
         console.log(sender.tab ?
                     "from a content script:" + sender.tab.url :
                     "from the extension");
         if (request.greeting == "hello")
         sendResponse({farewell: "goodbye"});
     });
    Copy the code
    • Content Script publishes information as a Message publish subscription
    • Js in Page Action or Browser Actionchrome.tabs.sendMessage()The last parameter is a callback function that receives data from the other side and synchronizes it to the UI
  chrome.tabs.sendMessage()
Copy the code
  1. Content Script has two types of injection: programmatic dynamic injection and declarative injection

  2. Dynamic injection: programmatic access activeTab permissions, use chrome. Tabs. ExecuteScript () to inject javascript code fragments, use chrome. Tabs. InsertCSS () into the CSS code snippet

     //manifest.json
     {
       "name": "My extension"."permissions": [
         "activeTab"],}Copy the code
Implement programmatic dynamic injection of Content Script into js in Page Action or Browser Action. The access and change the DOM properties are on the web page ` ` ` js chrome. Runtime. OnMessage. AddListener (function(message, callback) {
    if"ChangeColor (message = =") {chrome. Tabs. ExecuteScript ({code:'document.body.style.backgroundColor="orange"'}); }}); / / you can inject a file chrome. Runtime. OnMessage. AddListener (function(message, callback) {
    if(message = = "runContentScript") {chrome. Tabs. ExecuteScript ({file:'contentScript.js'}); }});Copy the code
  1. Declarative injection, defined in manifest.json using content_scripts
  {
      "name": "My extension"."content_scripts": [{"matches": ["http://*.nytimes.com/*"]."css": ["myStyles.css"]."js": ["contentScript.js"]}],... }Copy the code
  • Matches: mandatory array used to match the address of the page injected with the Content Script. Wildcards can be used to refer to characters of any length: ‘*’; ‘? ‘refers to a single character
  • CSS: Selectable arrays are injected in the order defined in the arrays before any DOM creation and presentation of the page
  • Js: Select an array and inject it in the order defined in the array
  • Run_at: Timing of Content Script injection
    • If it is document_start, the file will be injected when all CSS is loaded, but the DOM is not created and no scripts are running
    • In the case of document_END, the file is injected immediately after the DOM is created, but before child resources such as images or frames are loaded
    • If it is document_IDLE, the browser will inject it sometime between the document_end and the window.onload event. The timing depends on the complexity of document loading and is optimized for faster page loading
{
    "content_scripts" : [{
      "matches" : ["* : / / * / *"]."js" : ["content.js"."jquery.js"]."css" : ["style.css"]."run_at" : "document_end"}}],Copy the code
  • Options_page Specifies the options page of the plug-in. After this option is configured, right-click the plug-in and an “Options” button will be displayed. After clicking the button, the page corresponding to the options_page will be displayed

    {
        "options_page":"options.html"
    }
    Copy the code

  • Chrome_url_overrides Sets the replaceable chrome default page

    • Newtab: opens the page when creating a label
    • Bookmarks: Bookmarks page
    • History: indicates the historical record
    {
        "chrome_url_overrides": {"newtab": "newTab.html"}}Copy the code

Commonly used Chrome API

chrome.tabs

  1. Chrome.tabs. Create (Object createProperties, function callback) creates a new label. Note: This method can also be used without requesting manifest label permissions. Parameters createProperties ( object )

    • WindowId (Optional Integer) Target window for creating new labels. The default is the current window.
    • Index (Optional INTEGER) Position of the label in the window. The value is between zero and the number of labels.
    • Url (Optional string) initial page for TAB navigation. The full URL must contain a prefix (e.g. ‘www.google.com’, not ‘www.google.com’). The relative URL is relative to the page where the extension is located, and the default is the new TAB page.
    • Selected (Optional Boolean) Indicates whether the tag becomes the selected tag. The default is true.
    • Pinned (optional Boolean) Whether the tag is fixed. The default value is false.
    • callback ( optional function )

    Callback function Callback parameters should be defined as follows:

    function(Tab tab) {… }; TAB (TAB) Details of the label created, including the ID of the new label.

  2. Chrome. Tabs. ExecuteScript (integer tabId, object details and function callback) to the page into the JavaScript script execution Parameters

    1. TabId (optional INTEGER) Label ID of the running script. Defaults to the TAB selected for the current window.
    2. The value can be code or file, but not both.
      • Code (optional string) Script code to execute.
      • File (optional string) Script file to be executed.
      • AllFrames (optional Boolean) when frames are true, execute scripts for allFrames. The default is false and only scripts are executed for top-level frames.
    3. Callback (optional function) Callback that will be called after all scripts are executed.
  3. Chrome.tabs. Query (Object queryInfo, function callback) retrieves TAB page information filtered by specific filtering criteria, or all TAB page information if there is no specific filtering criteria

    1. QueryInfo is a specific attribute used to filter tabs. Common attributes are :(all attributes are Boolean values)

      • Whether the active TAB is active in their window
      • CurrentWindow whether the TAB is in the currentWindow
          chrome.tabs.query({
              active:true.currentWindow:true
          },function(tabs){
              / /...
          })
      Copy the code
    2. Callback is a callback function that retrieves information about a particular TAB page. The parameter is tag information

Chrome. contextMenus current page, select the content and then right-click the content to display

  1. Set permissions in manifest.json{"permissions": ["contextMenus", "storage"]}
  2. In background.js, in the callback function after initializationchrome.contextMenus.create({})Create a content directory
    chrome.runtime.onInstalled.addListener(function() {
     / /...
         chrome.contextMenus.create({
             "id": "sampleContextMenu"."title": "Sample Context Menu"."contexts": ["selection"]}); });Copy the code

Plug-in installation

  1. The extension management page is displayed. Chrome :// Extensions
  2. Enable ‘Developer Mode’
  3. Select ‘Load unzipped extension’ and upload your local development directory
  4. You can use ‘package extensions’ to generate extensions with the.ctx suffix and publish them to the Google Marketplace

Plug-in to debug

Note:

  • Each time the page is refreshed, the popup.html resource specified by browser_action or page_action is executed
  • Js resources specified by background are executed only when the plug-in is installed and remain in the process after that

Commissioning procedures

  1. Right-click the plug-in icon in the browser toolbar
  2. Click ‘Review pop-ups’ to access the console
  3. Switch to the Source bar to see the resource specified by browser_action or page_action, and set a breakpoint
  4. Switch to the Console bar and type location.reload() to see that the original page is reloaded, browser_action or page_action resources are reexecuted, and it stops at the breakpoint set and waits for debug

Refer to the link

How to write a Chrome extension from scratch