Google Chrome extension v3 version summary

foreword

I used the Google Chrome extension v2 a few years ago, and today I wanted to write an extension and found a lot of problems, and then I wanted to write an article to summarize. There is a big gap between v3 and v2. For details, you can go to the official website document

start

Before we start, let’s introduce a few websites, Google’s extended official website (over the wall-English) , Google’s extended Chinese website

project structure

Note 1 (used by service-worker)

service-worker.js is background.js and it must be in the root directory

ps: If you want to see it running, you need to open the console for the extension separately (extension - three dots - review popup content)

 Note 2 (manifest.json configuration)

{
    "name": "Getting Started Example",
    "version": "1.0",
    "description": "Build an Extension!",
    "manifest_version": 3,
    "permissions": [
      "declarativeContent", 
      "storage", 
      "activeTab"
    ],
    "externally_connectable": {
      "matches": ["*://*.xxxxxx.com/*"]
    },
    "background": {
      "service_worker": "service-worker.js"
    },
    "content_scripts": [
      {
        "matches": ["<all_urls>"],
        "js": ["js/jquery-1.8.3.js", "js/content.js"]
      }
    ],
    "web_accessible_resources": [
        {
            "matches": ["<all_urls>"],
            "resources": [ "js/inject.js", "js/jquery-1.8.3.js"]
        }
    ],
    "action":{
        "default_popup": "popup.html",
        "default_icon": "img/1.png",
        "default_title": "Latest Covid Report"
    },
    "icons": {
      "16": "img/1.png",
      "32": "img/1.png",
      "48": "img/1.png",
      "128": "img/1.png"
    }
  }
   

Note 3 (How to send a request)

content.js

chrome.runtime.sendMessage(
        {
         type: 'post',
         url: "https://xxxx.com/api/users/login",
         data: {
             url: 'test'
         }
        },
        function response(res) {
            console.log("回调...")
            console.log(res)
        }
    )

service-worker.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log("addListener...")
    console.log(request)
        switch(request.type) {
            case 'get':
                fetch(request.url)
                    .then(function(response) { sendResponse(response.json()) })
                .then(function(json) { sendResponse(json) })
                .catch(function(error) { sendResponse(null) });
            break;
            case 'post':
                fetch(request.url, {
                    method: 'POST',
                    mode: 'cors',
                    credentials: 'include',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: JSON.stringify(request.data)
                })
                    .then(function(response) { 
                        console.log(response)
                        sendResponse(response.json())
                    })
                    .then(function(json) {
                        console.log(json)
                        sendResponse(json)
                    })
                    .catch(function(error) {
                        console.log(error)
                        sendResponse(null)
                    });
            break;
            // 你可以定义任意内容,使用sendResponse()来返回它
            case 'test':
                sendResponse({'msg': 'test'});
            break;
    }
});

Note 4 (how to inject js)

content.js

// 可以操作当前页面中的DOM
$(document).ready(function() {

    console.log("---加载content.js---");
 
    // 注入inject.js
    injectCustomJs();
 
});

function injectCustomJs() {
    let jsPath = 'js/inject.js';
 
    var temp = document.createElement('script');
    temp.setAttribute('type', 'text/javascript');
    // 获得的地址类似:chrome-extension://ihcokhadfjfchaeagdoclpnjdiokfakg/js/inject.js
    temp.src = chrome.runtime.getURL(jsPath);
    temp.onload = function() {
        // 执行完后移除掉
        this.parentNode.removeChild(this);
    };
    // 挂载
    document.head.appendChild(temp);
}

inject.js

// 可以访问当前页面中的js
$(document).ready(function() {
    console.log("---inject.js---");
    console.log(window);
});

Summarize

In fact, I use it very shallowly, so there is nothing to summarize, read more documents and Baidu!

Guess you like

Origin blog.csdn.net/echo_Ae/article/details/124800000