Skip to content

Chrome插件-入门(V2版本)

一个简单的Chrome插件大致组成部分

  • content_script.js:在网页加载完成后,可以和网页交互,资源访问;
  • background.js:一个在浏览器后台常驻的文件,可以访问大部分chromeAPI;
  • popup.html:点击browser_action或者page_action图标时打开的一个小窗口网页,焦点离开网页就立即关闭(生命周期结束),一般用来做一些临时性的交互;
  • popup.js:在popup.html中加载,负责html的逻辑部分;

manifest.json 文件清单

json
{
  "name": "Chrome插件名称",
  "description": "Build an Extension!",
  "version": "1.0",
  
  "manifest_version": 2, //mv2(具体版本根据谷歌商店最新要求来定,最新是3)
  
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  }, //v2写法
  
  "background": {
    "service_worker": "background.js"
  }, //v3写法
  
  "permissions": ["storage"],
  
  
  // 浏览器右上角图标设置,browser_action、page_action、app三选一
  "page_action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "images/get_started16.png",
      "32": "images/get_started32.png",
      "48": "images/get_started48.png",
      "128": "images/get_started128.png"
    }
  },
  
  "content_scripts":{
    "scripts":[],
    "css":[]
  }
}
  • manifest_version:1,2,现在Chrome商店要求的最新版本是3。版本不同,manifest.json内指定的属性写法和插件功能开发用到的API会有些许不同;
  • background:后台脚本和许多其他重要组件必须在清单中注册。在清单中注册一个后台脚本会告诉扩展程序引用哪个文件,以及该文件应该如何运行;
js
chrome.runtime.onInstalled.addListener(function() {
  chrome.storage.sync.set({color: '#3aa757'}, function() {
    console.log("The color is green.");
  });
});
  • permissions:大多数使用到的API都需要在这里注册,否则将无权使用;
  • page_action.default_popup:引入用户界面,主流都是通过一个弹出框popup.html
html
<!DOCTYPE html>
<html>

<head>
    <style>
        button {
            height: 30px;
            width: 30px;
            outline: none;
        }
    </style>
</head>

<body>
    <button id="changeColor"></button>
    <script src="popup.js"></script>
</body>

</html>
  • page_action.default_icon:插件默认图标(需要制定特殊的规格字段,可选有:16,32,48,128...)

从本地加载插件

由于新开发的插件未发布到谷歌商店,所以只能从本地加载,这也是开发调试阶段的必经之路。

和V3的最大差异

移除了evel这种方式运行代码字符串的权限,代码字符串必须保存到具体的js文件中,并通过新的API来调用。

学习文档

MV2文档:https://developer.chrome.com/docs/extensions/mv2/getstarted/ MV3文档:https://developer.chrome.com/docs/extensions/mv3/getstarted/

Released under the MIT License.