This is the 8th day of my participation in the August More Text Challenge


Series of articles:

  • Introduction to Browser Plug-ins
  • Manifest V3
  • Essential concept for browser plug-in development – user interaction
  • Essential concepts for browser plug-in development – Common techniques
  • Essential concepts for browser plug-in development – Customizing the browser experience
  • Essential concepts for browser plug-in development – customizing the Web experience
  • Key concepts for browser plug-in development — Experience optimization
  • Browser plug-in development and debugging

Action

Reference:

  • chrome.action API
  • An official example of Action

The interactive control refers to the extension icon in the browser toolbar, for the user to click, can perform a predetermined operation. It can also be used as a portal to invoke other interactive controls, such as tooltip boxes when hovering and popup boxes when clicked.

💡 has API Chrome. browserAction (browser-level buttons that respond to all pages) and API Chrome. pageAction (pages that respond to specific matching criteria) in the MV2 version; Action API, which functions somewhat like Browser Action of MV2. If you want to implement functions similar to Page Action, please refer to the official example.

  • Json option, such as specifying the relative path of the icon file or the HTML file of the popup box if popup is used.

    {
      // ...
      "action": {
        // Icon file
        "default_icon": {              // optional
          "16": "images/icon16.png".// optional
          "24": "images/icon24.png".// optional
          "32": "images/icon32.png"    // optional
        },
        / / prompt dialog box
        "default_title": "Click Me".// optional, shown in tooltip
        / / the pop-up box
        "default_popup": "popup.html"  // optional}},Copy the code

    💡 Even if the action option is not set in the extender’s configuration manifest, it can be displayed in the browser toolbar using a default icon, usually referred to as an icon with a gray background and the extender’s initials.

  • icon

    The default height and width of an icon are 16 DIPs (Device-Independent Pixels). It is recommended to set multiple sizes of ICONS. The browser will use appropriate files. The icon file format should be supported by Blink rendering engine, such as PNG, JPEG, BMP, ICO, etc. SVG does not support it. If the extension program is decompressed, only the PNG format is supported.

    In addition to providing a fixed file in the manifest.json option action.default_icon, there is also a programmatic way to set the icon using the method chrome.action.seticon (), you can set different image paths according to the conditions. Canvas can also be used to create images. ⚠️ This method is used to set still images, not gifs.

    const canvas = new OffscreenCanvas(16.16);
    const context = canvas.getContext('2d');
    context.clearRect(0.0.16.16);
    context.fillStyle = '#00FF00';  // Green
    context.fillRect(0.0.16.16);
    const imageData = context.getImageData(0.0.16.16);
    chrome.action.setIcon({imageData: imageData}, () = > { / *... * / });
    Copy the code
  • Prompt box

    Tooltip is a box that displays when the user hovers over the icon, and you can set a short text to indicate the name of the extension.

    💡 When the icon button is focused, it can be recognized by screen reading software to enhance the accessibility of the extension.

    In addition to setting text in the manifest.json option action.default_title, you can also set it using the method chrome.action.settitle ().

  • pop-up

    Popup is a popup box that appears when the user clicks on the icon. It is actually an HTML page with a limited size (minimum height and width 25px, maximum height 600px, maximum width 800px). The default size is content-based.

    In addition to setting up the popup page in the manifest.json option action.default_popup, you can also use the method chrom.action.setpopup () to dynamically update the path to the HTML file that the popup points to.

  • tag

    Badge is a text added to the icon, and allows setting the background color, generally used to show the status of the extension, such as the update of a new version can display new, if the extension with statistical function can form the value, etc..

    ⚠️ Because markup space is limited, it is generally limited to four or fewer characters

    Through the method of chrome. Action. SetBadgeText () tag set text; By chrome. Action. SetBadgeBackgroundColor () tag set the background color

    chrome.action.setBadgeBackgroundColor(
      {color: [0.255.0.0]},  // Green
      () = > { / *... * /}); chrome.action.setBadgeBackgroundColor( {color: '#00FF00'.// Also green
      () = > { / *... * /}); chrome.action.setBadgeBackgroundColor( {color: 'green'},  // Also, also green
      () = > { / *... * /});Copy the code
  • Action can have different states on each TAB page. For example, different badge content can be set for different TAB pages

    function getTabId() { / *... * /}
    function getTabBadge() { / *... * /}
    
    chrome.action.setBadgeText(
      {
        text: getTabBadge(tabId),
        tabId: getTabId(),
      },
      () = >{... });Copy the code

    💡 If the tabId option for the first argument to the setBadgeText method is omitted, the tag is used as a global setting, whereas if tabId is provided, it is for a specific TAB page and has a higher priority, overwriting the tag text for the global setting.

  • By default, action ICONS are clickable on all tabs. You can manually control the response status of an action by using the chrome.action.enable() or chrome.action.disable() methods. This affects the display of popup or the distribution of corresponding events listened on by Chrome.action.onclicked.

Context Menu

Reference:

  • chrome.contextMenus API
  • Official example about Context Menu

This interactive control refers to the browser’s right-click menu, to which you can add options through the extension. In addition to the entire page, you can also add right-click menu items for specific DOM elements, or action ICONS.

  • To use the control, you need to declare registration in the permissions option of the manifest manifest.json. To make it easier to match menu options with extensions, you need to specify icon files in the ICONS option of the configuration list, preferably in multiple sizes of image files.

    {
      // ...
      "permissions": [
        "contextMenus"]."icons": {
        "16": "icon-bitty.png"."48": "icon-small.png"."128": "icon-large.png"}},Copy the code
  • Use chrome. ContextMenus. Create ({}, the callback ()) for the extension to create their own menu items, it can receive two into the parameter, the first parameter is the configuration object, the second parameter is the callback function. Return value The unique ID value of this menu option.

    There are several options for configuring an object, which are commonly used as follows:

    • idAssigns a unique ID to the current menu option
    • title(Must be, unless the menu option is of type splittertype: "separator") menu options
    • typeThe type of menu option. The default value isnormal“Is a normal menu option, and it could becheckbox,radio,separator
    • contextsArray that limits menu options to appear inTo which element of the pageWhen you right-click, the default is['page']That is, when you right-click anywhere on the entire page, the menu option appears in the menu
    • parentIdID of the parent menu of the current menu option
    • onclickListen for the menu option’s click event and the event handler that executes when the menu option is clicked, with two input argumentsinfo(information for this menu option) andtabIncoming (information for the current TAB)

    The (optional) back function is executed when the user right-clicks and the menu option is created

  • To use chrome. ContextMenus. Update (menuItemId, {}, the callback ()) to update a given menu options, the first parameter is the only ID value menu options, The second parameter is a configuration object (method and chrome. ContextMenus. The create () the configuration of the object can use options), the third parameter is the callback function (optional), after the update the menu options.

The 💡 browser’s right-click menu is global and can appear on any page, even the file:// or chrome://URLs page. If you want to control the menu options to appear on a specific page, you can create() or update() the menu options Configure the object’s option documentUrlPatterns to limit the display of menu items to a specific URL page or

  • Method of usechrome.contextMenus.remove(menuItemId, callback())Dynamically deletes created menu options. (Optional) The callback function is executed after the specified menu option is removed. If you want to remove all menu options created by the extender, use methodschrome.contextMenus.removeAll(callback())Its (optional) callback is executed after the menu option is deleted.
  • Multiple menu options can be created, but if there are more than one, the browser will automatically group them into a secondary menu
  • Method of usechrome.contextMenus.onClicked(callback())Listen for the click event of the extender menu option and execute the corresponding event handler, which takes two input argumentsinfoInformation about the menu option being clicked,tabTAB page Information.

Omnibox

Reference:

  • chrome.omnibox API
  • An official example of the Omnibox

The interactive control refers to the search keywords on the address bar. When the user inputs the corresponding keywords in the address bar, the Omnibox will be triggered (the corresponding extension program will be aroused). Then the user will directly interact with the extension program by inputting content in the address bar. A list of search suggestions is set up in the extender, and when the user enters a vague match, the suggestion is displayed in a Dropdown.

  • To use this control, you need to declare registration in the option Omnibox of the manifest manifest. When the Omnibox is triggered, the extension icon (shown as a gray scale) and the name are displayed on the left side of the address bar. To facilitate identification, you need to specify the icon file in the ICONS option of the configuration list, preferably providing image files of various sizes (default ICONS 16px high and wide).

    The interaction logic of the control is set in the service worker of the background script (the registration needs to be declared in the option background-service_worker of the manifest.json configuration), based on the principle of event listening-response.

    {
      // ...
      "background": {
        "service_worker": "background.js"
      },
      "omnibox": { "keyword" : "demo" },
      "icons": {
        "16": "icon-bitty.png"."48": "icon-small.png"."128": "icon-large.png"}},Copy the code

    The example above sets the Omnibox trigger keyword for the extension to Demo. When the user types Demo in the address bar, an option for the extension name is displayed in the drop-down box. You can click the option, press Tab, or type Space to trigger the Omnibox.

  • Common apis used to listen for events are as follows:

    • OnInputChanged Triggered when the user enters the address bar after entering Omnibox mode.

      chrome.omnibox.onInputChanged.addListener((text, suggest) = > {
        if(! text)return;
        suggest([
            {
                content: text,
                description: `search for ${text}`})});Copy the code

      The event handler takes two input arguments. The first argument, text, is what the user input (a string), and the second argument, suggest, is a method that receives an array of suggestresults and passes those suggestresults back to the browser. It is displayed in the drop-down box in the address bar.

      💡 SuggestResult is an object for the user to select from and includes the following attributes:

      • contentWhat is actually entered into the address bar, and what is passed to the extender when the user selects the suggested option
      • deletableIndicates whether the option can be deleted by the user
      • descriptionDescription content, displayed in the drop-down box of the address bar, can contain XML-style style modifications. But you can’t have fiveXML escape characters.

      💡 method can use chrome. The omnibox. SetDefaultSuggestion (the suggestion) to set the default recommended options, this method takes the reference is an incomplete suggestionResult object, not the content attribute, It’s similar to the placeholder in the input box. When the Omnibox is triggered, the default suggestion appears in the first drop-down box in the address bar before the user has entered anything.

      ⚠️ According to a Bug report, DomParser needs to be called because the search suggestion content of Omnibox supports XML, but the background script is migrated to service worker in MV3 version, and the running environment does not have DomParser, so an error will be reported. The search suggestion option cannot be displayed properly.

    • OnInputEntered fires the callback function after the user chooses to execute a suggested option.

      chrome.omnibox.onInputEntered.addListener((text, disposition) = > {
        if(! text)return;
        console.log('inputEntered: ' + text);
        // Encode user input for special characters , / ? : @ & = + $#
        var newURL = 'https://www.google.com/search?q=' + encodeURIComponent(text);
        chrome.tabs.create({ url: newURL });
        console.log(disposition)
      });
      Copy the code

      The event handler takes two arguments, the first text is what was entered into the address bar, and the second disposition is the setting of the search window. There are three possible outcomes:

      • CurrentTab searches the currentTab

      • NewForegroundTab Creates a TAB for searching and switches to the TAB

      • NewBackgroundTab Creates a TAB for searching but does not change the TAB

      The above example calls the chrome.tabs. Create () method to search on the currentTab, so the terminal prints the value currentTab

Override Pages

Reference:

  • Overriding Chrome pages

  • An official example of Override Pages

    • HistoryOverride (MV2 version)
    • Blank_ntp (MV2 version)
    • Override_igoogle (MV2 version)

The interactive control is implemented by overwriting pages. The extension can overwrite three special Chrome pages:

  • Bookmark Manager: Bookmark Management pagechrome://bookmarks
  • History: History pagechrome://history
  • New Tab: Creates a Tabchrome://newtab

💡 Each extension can only override the above three special Chrome pages, and each special Chrome page can only be overridden by one extension. In addition, new tabs cannot be overwritten in stealth mode.

  • Json chrome_url_overrides, which sets the page to be overridden as one of bookmarks, history, and newtab. Property value is the relative path of the HTML page document to replace.

    {
      // ...
      "chrome_url_overrides" : {
        "newTab": "newPage.html"},... }Copy the code
  • To provide a better user experience, replacement pages should follow these guidelines:

    • The page file size should be small to facilitate quick loading and display and to avoid blocking rendering with synchronous access to network or database resources.
    • Contains explicit information telling the user that they are currently viewing a special page of Chrome.
    • Do not use the input box focus function when creating a new TAB, because the address bar of the TAB gets the focus first.

Commands

Reference:

  • chrome.commands API
  • An official example of Commands

The interactive control refers to the use of shortcut keys to operate extensions, which can be used to activate actions or execute specific commands.

💡 all shortcuts extension in chrome: / / extensions/shortcuts, in which the user can modify the composite value of shortcut keys, or the local and global applicability of shortcuts.

  • Json. The value of this option is an object, the property name is a name describing the command, and the property value is an object about the shortcut definition. There are two options:

    • suggested_key(Optional) Declare the default shortcut key. The value can be a string representing the (cross-platform) shortcut key, or an objectFor different system platformsSet different shortcut keys, which the system platform supportsdefault,chromeos,linus,mac,windows. If this optionomit, the command does not have the corresponding trigger shortcut key.Wait for the user to set it to take effect.
    • descriptionA string that informs the user of the function of the shortcut key, which is displayed in the extension’s shortcut management interfacechrome://extensions/shortcutsIt is required for the standard Commands shortcut and optional for Action Commands.
    {
      // ...
      "commands": {
        "run-foo": {
          "suggested_key": {
            "default": "Ctrl+Shift+Y"."mac": "Command+Shift+Y"
          },
          "description": "Run \"foo\" on the current page."
        },
        "_execute_action": {
          "suggested_key": {
            "windows": "Ctrl+Shift+Y"."mac": "Command+Shift+Y"."chromeos": "Ctrl+Shift+U"."linux": "Ctrl+Shift+J"}}}},Copy the code

    💡 where _execute_action is the reserved attribute, which defines the shortcut key for activating the action (for MV2, there are the _execute_browser_action and _execute_page_action reserved attributes, Setting the browser action and Page Action shortcut keys to activate respectively). Activating the action shortcut keys cannot trigger the command. OnCommand event.

    💡 If the default shortcut keys of a newly installed extension conflict with those of other installed extensions, the browser will not register these shortcut keys for the later installed extensions to avoid overwriting the existing shortcut keys. In order to avoid make the user feel shortcuts “without failure” phenomenon, we should adopt the following method is more robust, when installing extensions chrome. Runtime. OnInstalled. AddListener check first shortcut conflicts, and inform the user

    // background.js
    
    // Only use this function during the initial install phase. After
    // installation the user may have intentionally unassigned commands.
    chrome.runtime.onInstalled.addListener((reason) = > {
      if(reason === chrome.runtime.OnInstalledReason.INSTALL) { checkCommandShortcuts(); }});function checkCommandShortcuts() {
      // Get the shortcut keys registered for the current plug-in
      chrome.commands.getAll((commands) = > {
        let missingShortcuts = [];
    
        for (let {name, shortcut} of commands) {
          // If the conflict fails to register the default shortcut key, the shortcut value is an empty string
          if (shortcut === ' ') { missingShortcuts.push(name); }}// If the extension does have a shortcut key conflict with another extension
        if (missingShortcuts.length > 0) {
          // Update the extension UI to inform the user that one or more
          // commands are currently unassigned.}}); }Copy the code
  • The shortcut key must contain Ctrl or Alt and is case-sensitive. You can use the following combination keys:

    • The lettersA-Z
    • The number keys0 ~ 9
    • Standard function keys
      • The general keyComma.Period.Home.End.PageUp.PageDown.Space.Insert.Delete
      • The direction keyUp.Down.Left.Right
    • Modifier keysCtrl.Alt.Shift.MacCtrl (macOS only), Command (macOS only), Search (Chrome OS only)

    💡 does not support Tab. Media keys cannot be combined with modifier keys.

  • In response to keyboard shortcuts, need the script in the background using the chrome.com mands. OnCommand. AddListener API for listening

    chrome.commands.onCommand.addListener((command) = > {
      console.log(`Command: ${command}`);
    });
    Copy the code

    💡 does not listen for action shortcuts, unlike standard commands shortcuts. Instead, listen for the DOMContentLoaded event in the popup script file.

  • By default, the registered shortcut is a local Chrome shortcut (the extension responds only when the browser is an active application on the current system) or can be set to a global shortcut in the shortcut definition object with the option Global: True. It is recommended that registration of global hotkeys be limited to Ctrl+Shift+[0..9] to avoid overwriting other system-level hotkeys.

    {
      // ...
      "commands": {
        "toggle-feature-foo": {
          "suggested_key": {
            "default": "Ctrl+Shift+5"
          },
          "description": "Toggle feature foo"."global": true}}},Copy the code

    💡 But Chrome OS does not support setting global shortcuts for extensions