首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >写个自己的chrome插件

写个自己的chrome插件

作者头像
Maic
发布2022-12-21 19:18:35
1.8K0
发布2022-12-21 19:18:35
举报
文章被收录于专栏:Web技术学苑Web技术学苑

有没有好奇chrome[1]插件是用什么做的?像类似掘金插件又是怎么实现的,当我安装稀土掘金插件后,我的导航页都被改掉了,因此你也可以做一个类似的插件,来导航你公司的一些产品,方便快捷的实现你的内部导航

在开始本文之前,主要是从零认识一个chrome插件,主要会从以下几点去认识chrome插件

  • 核心配置manifest.json配置,必不可少的几个配置
  • popup为插件内容文件
  • backgroundcontent通信,popupcontent通信
  • chrome.runtime几个通信API

正文开始...

首先预知的几个文件

manifest.json,必须在插件根目录上新建一个这样的文件,我们从官网查看更多的manifest[2]信息


{
    // 必不可少
    "manifest_version": 3, // 扩展插件版本必须是2以上
    "name": "Maic_test_chrome", // 扩展名称
    "description": "lesson demo", // 扩展描述
    "version": "1.0",
    // 可选
    "action": {
        "default_popup": "popup/index.html", // 默认的页面
        "default_icon": "logo.png" // 浏览器扩展插件显示图标
    },
    // 在插件列表里显示不同尺寸的图标
    "icons": {
        "16": "images/icon-16.png",
        "32": "images/icon-32.png",
        "48": "images/icon-48.png",
        "128": "images/icon-128.png"
    }
}

让当前网页加载一个脚本

content_scripts指定加载对应脚本js,css注意matches中匹配的是当前访问的url,当选择<all_urls>时,匹配任何url,必须要有matches[3]否则不会生效


 "content_scripts": [
        {
            "js": [
                "scripts/content.js"
            ],
            "matches": [
                "https://*.wmcweb.cn/*",
                "<all_urls>"
            ]
        }
    ]

background增强浏览器事件程序的js


{
 "background": {
        "service_worker": "background.js"
  }
}

background.jscontent.js通信

background.js在插件页面加载,background.js调用onMessage.addListener接收content.js发送过来的数据


function callback(info, curent, sendToContent) {


}
chrome.runtime.onMessage.addListener(callback)

// background.js 在插件页面加载
const user = {
    username: 'Maic'
};
// 调用onMessage.addListenter
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('background.js', message, sender)
    // 2. A page requested user data, respond with a copy of `user`
    if (message === 'get-user-data') {
        sendResponse(user);
    }
});

content.js在你指定的匹配域名页面加载,与当前浏览器加载的页面同环境

content.jscontentbackground.js发送信息


chrome.runtime.sendMessage(info, callbackResponse)

// sendMessage content.js
chrome.runtime.sendMessage('get-user-data', (response) => {
    console.log('received user data', response);
});

popup.jscontent.js通信

popup页面需要查找当前激活的tabs


// popup.js
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {}, function (response) {
            console.log(response, 'content.js回传过来的信息');
   });
});

content.js接收信息


function callback(request, sender, sendResponse) {}
chrome.runtime.onMessage.addListener(callback)

content.js详细代码参考以下


// content.js
console.log('loader-content')
// 1. content向service worker发送信息
chrome.runtime.sendMessage('get-user-data', (response) => {
    // 2,接受service worker回调过来的信息
    console.log('received service worker data', response);
});


const render = ({ style, title }) => {
    const boxDom = document.querySelector('.box');
    const contentDom = document.querySelector('.content');
    const resultDom = document.querySelector('.result');
    boxDom.style.width = style.width;
    boxDom.style.height = style.height;
    boxDom.style.backgroundColor = style.backgroundColor;
    contentDom.innerText = title;
    resultDom.innerText = JSON.stringify({ ...style, title }, null, 2)
}
// 接收popup.js发送过来的信息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log('content', request, sender);
    const {
        inputColorValue,
        titleValue,
        widthValue,
        heightValue } = request;
    const style = {
        width: `${widthValue}px`,
        height: `${heightValue}px`,
        backgroundColor: inputColorValue
    }
    const receivePopupInfo = {
        style,
        title: titleValue
    }
    // 向popup.js回传信息
    sendResponse(receivePopupInfo)
    render(receivePopupInfo)
});

background.js参考如下


const user = {
    username: 'Web技术学苑'
};
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('background.js', message, sender)
    if (message === 'get-user-data') {
        sendResponse(user);
    }
});

popup.js参考如下


const $ = id => document.getElementById(id);
function setBadge() {
    const inputColorValue = $('color-input').value;
    const titleValue = $('title-input').value;
    const widthValue = $('width-input').value;
    const heightValue = $('height-input').value;
    const info = {
        inputColorValue,
        titleValue,
        widthValue,
        heightValue
    }
    chrome.action.setBadgeText({ text: inputColorValue });
    // 扩展脚本向content发出信息
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        console.log(tabs)
        chrome.tabs.sendMessage(tabs[0].id, info, function (response) {
            console.log(response, 'content.js回传过来的信息');
        });
    });
}


$('submit').addEventListener('click', setBadge);
['width', 'height'].forEach(dom => {
    const curent = $(`${dom}-input`);
    curent.addEventListener('change', (evt) => {
        $(`${dom}-result`).innerText = evt.target.value;
    })
});

我们再看下popup.html


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="popup.css" />
  </head>
  <body>
    <div id="app">
      <div>title: <input type="text" value="我是标题" id="title-input" /></div>
      <div>color:<input type="color" id="color-input" /></div>
      <div>
        width: <input type="range" value="30" id="width-input" max="1000" />
        <span id="width-result">30</span>
      </div>
      <div>
        height: <input type="range" value="30" id="height-input" max="1000" />
        <span id="height-result">30</span>
      </div>
      <button id="submit">确定</button>
    </div>
    <script src="./popup.js"></script>
  </body>
</html>

当你打开浏览chrome://extensions/然后添加插件04-demo

在打开一个测试页面

我通过插件中的popup.jscontent.js通信,就可以修改我当前页面上的元素了

另外推荐一个chrome插件官方的例子chrome-extensions-samples[4],看完一些例子多插件哟更深刻的认识,在下一节里,我会利用chrome内置缓存能力做一些与我们实际业务相关的例子。

总结

  • 一个chrome插件基础文件manifest.json几个比较的参数,加载插件根目录必须要有个文件,且manifest_version2版本上
  • popup.jscontent.js交互,content.js是独立于插件外部脚本,当匹配对应网页时,可以利用content.js控制当前网页
  • background.js是运行插件增强js,我们可以在这background.js控制chrome插件,或者与popup.js的通信
  • chrome核心api,chrome.runtime.onMessagechrome.runtime.sendMessage,chrome.tab.query的使用
  • 本文示例code example[5]

参考资料

[1]chrome: https://developer.chrome.com/docs/extensions/mv3/

[2]manifest: https://developer.chrome.com/docs/extensions/mv3/manifest/

[3]matches: https://developer.chrome.com/docs/extensions/mv3/content_scripts/#programmatic

[4]chrome-extensions-samples: https://github.com/GoogleChrome/chrome-extensions-samples

[5]code example: https://github.com/maicFir/lessonNote/tree/master/chrome-plugin/04-demo

最后,看完觉得有收获的,点个赞,在看,转发,收藏等于学会,欢迎关注Web技术学苑,好好学习,天天向上!

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2022-11-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Web技术学苑 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 让当前网页加载一个脚本
  • background增强浏览器事件程序的js
  • background.js与content.js通信
  • popup.js向content.js通信
  • 总结
  • 参考资料
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档