Write a Chrome browser plug-in (manifest v3)

Table of contents

1. Create manifest.json file

2. Start writing the popup page and corresponding logic.

2.1 popup page

2.2 Running background.js in the background 

2.3 content.js 

2.4 js file of popup page

3. Chrome browser loads this project

4. Reference documents


1. Create manifest.json file

First, you need to create a manifest.json file in the root directory of the project. This file describes the relevant information of the plug-in, as shown below:

  • description: description field of the plug-in
  • name: the name of the plug-in
  • manifest_version: version of the chrome plug-in (currently the latest version is version 3)
  • version: project version
  • author: project author
  • default_locale: default is Chinese

icon icon, and the path information corresponding to the icons of different sizes below.

 Web-accessible resource paths and corresponding matching rules.

Permission configuration list:

  • storage chrome storage related permissions.
  • tabs browser tab permissions
  • background Permission to run in the background
  • scripting script execution permissions
  • contextMenus right-click menu permissions
  • Some other permissions...

Native permissions: match all

Action includes the default title name, default icon, and path corresponding to the default popup.

Running in the background, the js file path corresponding to service_worker.

The content script includes:

  • matches matching rules
  • js content script path
  • Whether all_frames supports iframe modification. 

The contents of the manifest.json file corresponding to the above are as follows:

{    
      "description": "这是一个解密的工具",
      "name": "my_chrome_plug",
      "manifest_version": 3,
      "version": "1.0.0",
      "author": "yixuan",
      "default_locale": "zh_CN",
      "icons": {
        "16": "static/img/icon.png",
        "48": "static/img/icon.png",
        "128": "static/img/icon.png"
      },
      "web_accessible_resources": [{
        "resources": [
          "static/js/*",
          "static/css/*",
          "static/img/*"
        ],
        "matches": [
          "<all_urls>"
        ]
      }],
      "permissions": [
        "storage",
        "tabs",
        "background",
        "scripting",
        "contextMenus"
      ],
      "host_permissions": [
        "<all_urls>"
      ],
      "action": {
        "default_title": "my_chrome_plug",
        "default_icon": "static/img/icon.png",
        "default_popup": "index.html"
      },
      "background": {
        "service_worker": "static/js/background.js"
      },
      "content_scripts": [{
        "matches": [
          "<all_urls>"
        ],
        "js": [
          "static/js/content.js"
        ],
        "all_frames": true,
        "run_at": "document_idle"
      }]
    }
    

2. Start writing the popup page and corresponding logic.

First, list the project directory structure:

2.1 popup page

Write a decoding gadget, 2 text field input boxes, and a decoding button. The corresponding page html is as follows:

<body>
    <div class="_content">
        <form class="form-inline">
            <div class="form-group">
                <textarea type="text" class="from-control" id="_input" rows="6" placeholder="请输入......"></textarea>
            </div>
        </form>
        <div>
            <button id="_button" type="button" class="btn btn-primary"> 解码 </button>
        </div>
        <div class="form-group">
            <textarea type="text" class="from-control" id="_output" rows="16"></textarea>
        </div>
    </div>
</body>

2.2 Running background.js in the background 

There are 2 functions written in this project:

  • Create right-click menu and menu click event logic
  • Monitor corresponding message events

The corresponding code is as follows:

// 创建右键菜单
chrome.contextMenus.create({
    id: "parent",
    title: 'DECODE 解码',
    contexts: ['page']
})
// 监听右键菜单单击事件,创建的tab标签页,指向的页面为index.html
chrome.contextMenus.onClicked.addListener((info, tab) => {
    if(info.menuItemId == 'parent') {
        console.log('menu......');
        chrome.tabs.create({
            url: "index.html" 
        })
    }
})
// 消息监听
chrome.runtime.onMessage.addListener((message) => {
    let keyArrys = Object.keys(message);
    let valueArrays = Object.keys(message);
    keyArrys && keyArrys.map((res, index) => chrom.storage.local.set({[res] : valueArrays[index]}))
})

2.3 content.js 

content.js shares DOM nodes with the target web page , but is isolated from the JS part of the target and cannot call each other.

Background.js can communicate with the js part of the popup page through the chrome api. Background.js can always accept messages sent by content.js, because background.js is always running in the background, while content.js can only be opened on the popup page. Only then can the corresponding message be received.

Next we start sending messages in content.js, as shown below:

async function sendMessage () {
    console.log("开始发送消息.............");
    await chrome.runtime.sendMessage(sessionStorage, function (res) {
        console.log("收到回复...............");
    })
}

2.4 js file of popup page

Start writing the corresponding decoding logic in the current js file. First, after the entire DOM is loaded, add the corresponding click event to the decoding button, and then start the decoding process, including processing of spaces, single and double quotes, etc.

The code looks like this:

function decode () {
    try {
        var inputValue = $("#_input").val().trim();
        var reg = /^['|"](.*)['|"]/;
        var responseParams = true;
        if (inputValue.includes("helloword")) {
            inputValue = inputValue.replaceAll("helloworld", "");
            responseParams = false;
        }
        inputValue = inputValue.replace(reg, "$1");
        var output = DECODE(inputValue);
        responseParams && output.res && (output.res = JSON.parse(output.res))
        $("#_output").val(JSON.stringify(output))
    } catch (error) {
        console.log(error)
    }
}

document.addEventListener('DOMContentLoaded', () => {
    $("#_button").click(() => {
        decode()
    })
})

3. Chrome browser loads this project

1. Click on the upper right corner of the browser->Extensions->Manage extensions, as shown in the figure below:

2. Click the upper right corner to open the development mode, then click the "Load unzipped extension" button and select your own project directory. As shown below:

3. Click the plug-in icon of this project in the upper right corner of the browser, a pop-up page will pop up, enter the content that needs to be decoded in the above input box, and then click the "Decode" button to output the corresponding decoded content into the input box below. As shown below:

4. For the plug-in right-click menu, place the mouse in a blank space on the web page, right-click the pop-up menu, and you can see the menu and icon you created. Then click the corresponding menu, and the browser will create a new tab page pointing to the pop-up page you configured. As shown below:

4. Reference documents

For other configurations or examples, please refer to the following documents:

Chrome official documentation (English version)

360 Chinese development documents

It is best to refer to the official chrome documentation and 360 documentation. The content inside is not the latest. It is the manifest v2 version. There are still some differences between v3 and v2. When developing, pay attention to the corresponding version of the following manifest.

 

Guess you like

Origin blog.csdn.net/u014388408/article/details/133270056