This is the 11th 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

Chrome provides a number of related apis to customize the browser experience:

  • Bookmarks management
  • Browsing Data Allows users to browse Data
  • Downloads Downloads management
  • Font Settings Indicates the Font Settings
  • History Browsing History
  • Privacy Privacy permission Settings
  • Proxy Proxy Settings
  • Sessions Queries and restores tabs or Windows from the browsing session
  • Tabs Creates, modifies, and rearranges Tabs
  • Top Sites accesses the web pages most frequently visited by users
  • Themes changes the look and theme of the browser
  • Windows creates, modifies, and rearranges browser Windows

Bookmarks

Reference:

  • Chrome.bookmarks API

  • An official example of Bookmarks

    • Bookmarks Basic (MV2 Version)
    • bookmarks

You can use extensions to customize your browser’s bookmark management behavior. In addition to customizing the bookmark management Page by overriding the Page, you can also manipulate bookmarks using a series of apis in Chrome.Bookmarks.

To use the Chrome.bookmarks API, you need to register the permission declaration in the manifest.json option permissions

{
  // ...
  "permissions": ["bookmarks"]}Copy the code

Bookmark data based on tree structure, each node object bookmarks. BookmarkTreeNode is a bookmark or a folder (also known as a group), it has many properties, listed below are a few commonly used:

  • childrenChild node list
  • idUnique identifier
  • indexIndex (must) in the parent folder (from0Start)
  • parentIdThe unique identifier of the parent folder (The root nodeOmit this property.
  • titleThe (required) name of the node displayed
  • urlBookmark link, folder can omit this property

⚠️ The root node is a folder and cannot be deleted. And you cannot rename special nodes (folders) 📁 Bookmarks Bar Bookmarks Bar and 📁 Other Bookmarks

Use the method chrome.bookmarks.create() to create a bookmark node that takes two inputs, the first being the node’s property and the second (optional) being the callback function

// Create a folder called Extension Bookmarks
chrome.bookmarks.create(
  {'parentId': bookmarkBar.id, 'title': 'Extension bookmarks'},
  function(newFolder) {
    console.log("added folder: "+ newFolder.title); });/ / create a bookmark, called Extensions doc, links to https://developer.chrome.com/docs/extensions
chrome.bookmarks.create({
  'parentId': extensionsFolderId,
  'title': 'Extensions doc'.'url': 'https://developer.chrome.com/docs/extensions'});Copy the code

Browsing Data

Reference:

  • chrome.browsingData API
  • An official example of Browsing Data (MV2 version)

The extender can delete user browsing data for a specific time period.

To use the Chrome.bookmarks API, you need to register the permission declaration in the manifest.json option permissions

{
  // ...
  "permissions": ["browsingData"]}Copy the code

Method of use chrome. BrowsingData. Remove () to delete user data.

// Delete a week's worth of data
const millisecondsPerWeek = 1000 * 60 * 60 * 24 * 7;
const oneWeekAgo = (new Date()).getTime() - millisecondsPerWeek;

// Delete all user operations
chrome.browsingData.removeCookies({
  "since": oneWeekAgo
}, callback;

const callback = function () {
  // Do something clever here once data has been removed.
};
Copy the code

💡 Deleting user data can take a long time (based on how much operation history data the user has generated), so it is recommended to set up the callback function (which is executed after the purge is complete) to inform the user of the latest status.

⚠ ️ method chrome. BrowsingData. Remove () may be in after clearing the cookies set them automatically, so that the account data synchronization function of normal operation, such ability can let the server has been synchronized to the corresponding data also cover removed; And how to use the chrome. BrowsingData. RemoveCookies clear cookies, will stop synchronization function.

💡 can pass a JSON object specifying which types of browser data to delete, or call corresponding methods to delete the corresponding types of user data.

// Delete the specified user operation data
chrome.browsingData.remove({
  "since": oneWeekAgo
}, {
  "appcache": true."cache": true."cacheStorage": true."cookies": true."downloads": true."fileSystems": true."formData": true."history": true."indexedDB": true."localStorage": true."passwords": true."serviceWorkers": true."webSQL": true
}, callback);
Copy the code

💡 can also delete user data under a specified page (or not) (for cookies, cache, storage (CacheStorage, FileSystems, IndexedDB, LocalStorage, ServiceWorkers, and WebSQL) types of data), can be in the method. Chrome browsingData. Remove () in the first parameter to the setting options origins or excludeOrigins

chrome.browsingData.remove({
  "origins": ["https://www.example.com"] {},"cacheStorage": true."cookies": true."fileSystems": true."indexedDB": true."localStorage": true."serviceWorkers": true."webSQL": true
}, callback);
Copy the code

Because cookies are domain-based, deleting cookies of a specific web page deletes all cookies under the domain name. For example, deleting https://www.example.com deletes all cookies under the.example.com domain name.

Downloads

Reference:

  • chrome.downloads API
  • Official example of Downloads (MV2 version)

The Chrome. Downloads API enables you to launch, monitor, manipulate, and search for downloads.

To use the Chrome.Downloads API, you need to register the permission declaration in the Manifest.json option Permissions

{
  // ...
  "permissions": ["downloads"]}Copy the code

History

Reference:

  • chrome.history API
  • Official example of History (MV2 version)

The extension can manipulate the browser’s history. In addition to customizing the history Page by overriding the Page, you can also manipulate the history using the Chrome.history API.

To use the Chrome.history API, you need to register the permissions declaration in the manifest.json option permissions

{
  // ...
  "permissions": ["history"]}Copy the code

💡 Browsing history is generated by different types of page transition type. For example, when a user clicks a link from one web page to another, the type of history generated is link.

Tabs

Reference:

  • chrome.tabs API
  • Official example on Tabs (MV2 version)

Extensions can create, modify, and rearrange tabs.

Although it is possible to use the API in the Chrome.tabs section without permission declaration, it is recommended to register permission declaration in the manifest.json option permissions, Permissions are required to access the attribute URL, pendingUrl, title, and favIconUrl of the label.

{
  // ...
  "permissions": ["tabs"]}Copy the code

Here are some common application scenarios:

  • Use the method chrome.tabs. Create () to open a web page in a new TAB

    // background.js
    // You can open the introduction page of the extension program after the successful installation
    chrome.runtime.onInstalled.addListener((reason) = > {
      if (reason === chrome.runtime.OnInstalledReason.INSTALL) {
        chrome.tabs.create({
          url: 'onboarding.html'}); }});Copy the code

    ⚠️ Content script Content scripts Cannot use method chrome.tabs. Create ()

  • Use chrome. Tabs. Query ({active: true, currentWindow: true}) to obtain the desired tabs

    // background.js
    async function getCurrentTab() {
      let queryOptions = { active: true.currentWindow: true };
      // The query returns a list of qualified TAB objects. There is only one current page, which can be retrieved directly by destructuring
      let [tab] = await chrome.tabs.query(queryOptions);
      return tab;
    }
    Copy the code

    ⚠️ content scripts Content scripts cannot use methods chrome.tabs.query()

  • Usage Chrome.tabs. Update () Updates the status of a TAB page

    // background.js
    function toggleMuteState(tabId) {
      chrome.tabs.get(tabId, async (tab) => {
        // Get the mute status of the TAB page and toggle
        letmuted = ! tab.mutedInfo.muted;// Update the mute status of the tabs
        await chrome.tabs.update(tabId, { muted });
        console.log(`Tab ${tab.id} is ${ muted ? 'muted' : 'unmuted' }`);
      });
    }
    Copy the code

    ⚠️ Content scripts Content scripts cannot be used with methods chrom.tabs. Get () and chrom.tabs. Update ()

  • Use chrome.tabs. Move () to rearrange tabs

    // background.js
    // Listen for TAB activation events (triggered when clicking the top bar of the browser to switch tabs)
    chrome.tabs.onActivated.addListener(activeInfo= > move(activeInfo));
    
    // Move the active TAB to the first position
    async function move(activeInfo) {
      try {
        await chrome.tabs.move(activeInfo.tabId, {index: 0});
        console.log('Success.');
      } catch (error) {
        // If the user is dragging and dropping tabs
        if (error == 'Error: Tabs cannot be edited right now (user may be dragging a tab).') {
          setTimeout(() = > move(activeInfo), 50); }}}Copy the code

Windows

Reference:

  • chrome.windows API

  • An official example of Windows

    • Merge_windows (MV2 version)
    • Inspector (MV2 version)

Extensions can create, modify, and rearrange browser Windows.

Because the Chrome. Windows API gets information about tabs, you need to declare tabs in the permissions option of the manifest.json configuration.

{
  // ...
  "permissions": ["tabs"],}Copy the code

💡 The current window is the window in which the extension is currently executing code, not necessarily the top or current focus window of the browser. For example, the extension opens an HTML document in a window and calls the chrome.tabs. Query () method in the document. The current window is the window in which the HTML document is located. In some cases there is no current window for background scripts.