chrome 插件开发教程

栏目: chrome 发布时间:2024-11-01

chrome 插件代码目录结构

|____background.js

|____icons

| |____logo.png

|____manifest.json

|____lib

| |____zepto.js

|____content.js

开发者工具增加菜单

manifest.json 中配置

"devtools_page": "devtools/devtools.html"

浏览器菜单栏增加popup

"browser_action": {
  "default_icon": {
    "19": "icons/19x19.png",
    "38": "icons/38x38.png"
  },
  "default_title": "That's the tool tip",
  "default_popup": "browser-action/popup.html"
},

右键菜单

https://open.chrome.360.cn/extension_dev/contextMenus.html https://groups.google.com/a/chromium.org/g/chromium-extensions/c/9K5Auvrilbo

/**
 * 创建一级菜单
 */
chrome.contextMenus.create({
  id: 'tides',
  title: 'tides',
  contexts: ['all']
})
/**
 * 创建二级菜单
 */
chrome.contextMenus.create({
  id: `dev`,
  parentId: 'tides',
  title: 'dev',
  contexts: ['all']
})

chrome.contextMenus.onClicked.addListener(info => {
  // 处理菜单点击事件
})

content 与 background 通信

// content.js
chrome.runtime.sendMessage({greet:'hello'},function (response) {
  console.log('content get response:', response);
})
// background.js
chrome.runtime.onMessage.addListener(function (request, sender,callback) {
  callback('hi!');
})

background.persistent

  • true 浏览器重启时会执行
  • false 只在插件初始化时执行一次

本文地址:https://www.tides.cn/p_chrome-plugin-develop

标签: chrome插件