谷歌扩展笔记

谷歌扩展学习

向大佬学习(参考文章)


个人理解

  • popupbackground传递信息
  • contentScriptbackground传递信息
  • popupcontentScript 使用
  • popup 运行开始于点击插件打开popup页面
  • background 运行开始于浏览器开启
  • contentScript 运行开始于页面开启
// popup / contentScript                                 // background
chrome.runtime.sendMessage(msg)                  --->    chrome.runtime.onMessage.addListener(msg => {})

// 长链接
let port=chrome.runtime.connect({name:'name'})   --->    chrome.runtime.onConnect.addListener(port => {
port.postMessage(msg)                            --->      port.onMessage.addListener(msg => {})
port.onMessage.addListener(msg => {})            <---      port.postMessage(msg)
                                                         })

// popup												 // background
chrome.tabs.query({								 --->    chrome.runtime.onMessage.addListener(msg => {})
  active: true,
  currentWindow: true
 }, tabs => {
  chrome.tabs.sendMessage(tabs[0].id, msg)
})

// 长链接
chrome.tabs.query({								 --->    chrome.runtime.onConnect.addListener(port => {
  active: true,											   
  currentWindow: true									   
 }, tabs => { 											  
  const port = chrome.tabs.sendMessage(					  
    tabs[0].id,									         
    { name: 'test' }
  )
  port.postMessage(msg)                            --->    port.onMessage.addListener(msg => {})
  port.onMessage.addListener(msg => {})            <---    port.postMessage(msg)
                                                         })
})


api

chrome
  .alarms                                                               // 定时器
    .create
      ({delayInMinutes: 1})

  .bookmarks                                                            // 书签 需在 permission申明
    .onCreated
      .addListener(() => {})                                            // 书签创建监听
    .getTree(res => {})                                                 // 获取整个书签栏数据(树形)
    .getSubTree(id, res => {})                                          // 根据id获取某个子节点(树形)
    .get(id, res => {})                                                 // id/[id]获取书签(数组)
    .getChildren(id, res => {})                                         // 获取指定id的书签的所有子节点(树形)
    .getRecent(10, res => {})                                           // 获取10个最近的书签
    .search('', res => {})                                              // string / {属性} 搜索书签
    .create({                                                           // 创建书签
      parentId,
      title,
      url                                                               // url为NULL或不传则新建书签文件夹
    })
    .move(id, {parentId}, res => {})                                    // 移动书签 返回新的书签对象 不能移动到 0 这个 root节点(只是记笔记还没试)
    .update(id, {}, res => {})                                          // {} 为修改的属性 返回新的书签对象
    .remove(id, res => {})                                              // 输出指定id的书签 或 空 书签文件夹(盲猜只能删最后一级,否则不需要removeTree,未尝试)
    .removeTree(id, res => {})                                          // 删除整个书签树

  .browserAction
    .setBadgeText({text: 'ON'}, () => {})                               // 图标文字
    .getBadgeText({}, res => {})                                        // 获取图标文字
    .setBadgeBackgroundColor({color: '#4688F1'})                        // 图标颜色
    .getBadgeBackgroundColor({}, res => {})                             // 获取图标背景色
    .setTitle({title: 'new title'}, () => {})                           // 设置扩展名
    .getTitle({}, res => {})
    .setPopup({popup: './popup2.index'}, () => {})                      // 设置popup页面
    .getPopup({}, res => {})                                            // 获取popup页面路径

  // 激活插件?需要在permission申明
  .declarativeContent
    .onPageChanged                                                      // url变更
      .addRules                                                         // 增加规则
        ([
          {
            conditions: [                                               // 规则的条件是 URL 中包含 focusnote
              new chrome.declarativeContent.PageStateMatcher({
                pageUrl: { urlContains: 'focusnote' }
              })
            ],
            actions: [new chrome.declarativeContent.ShowPageAction()]
          }
        ])

      .removeRules                                                      // 移除规则
        (undefined, () => {})
	
  .extension
  	.onMessageExternal
	.onMessage
	.onConnectExternal
	.onConnect
	.sendNativeMessage
	.sendMessage
	.connectNative
	.connect
	.onRequest
	.sendRequest
	.onRequestExternal

  .runtime                                                              // 运行
    .onInstalled                                                        // 初始化扩展程序
      .addListener

    .connect({name: 'key'})                                             // 长连接通信
    // 连接上时
    .onConnect
      .addListener
        (port () => {
          port
            .onMessage
              .addListener
                (mes => {})                                             // 收到的信息
        })

    .sendMessage()
    
    .onMessage                                                          // 收到信息时
      .addListener
        ((message, sender, () => {}) => {})
    
    .onSuspend                                                          // 监听页面销毁
      .addListener
        (() => {})

  // 右键菜单 需在permission申明
  .contextMenus
    .create                                                             // 创建菜单
      ({
        id: key,                                                        // 自定义key 点击后返回的值,大概
        title: title,                                                   // 显示的值
        type: "normal",                                                 // 默认
              "checkbox",                                               // 多选
              "radio",                                                  // 单选
              "separator"                                               // 分割线
        contexts: [
          "all",                                                        // 全部
          "page",                                                       // 页面
          "frame",                                                      // iframe标签
          "selection",                                                  // 选中时
          "link",                                                       // 链接
          "editable",                                                   // 可编辑域
          "image",                                                      // 图片
          "video",                                                      // 视频
          "audio",                                                      // 音频
          "launcher",
          "browser_action",
          "page_action"
        ],
        parentId: '',                                                   // 指定父菜单id,设置子菜单 可选
        visible: true,                                                  // 显示 可选
        checked: true                                                   // 默认选中 可选
      })

    .update(id, {}, () => {})                                           // 根据id更新菜单
    .remove(id, () => {})                                               // 根据id移除菜单
    .removeAll(() => {})                                                // 移除所有菜单
    .onClicked
      .addListener(key => {})                                           // 点击监听

  // 事件过滤(暂不清楚)
  .webNavigation
    .onComplete
      .addListener
        (
          () => {},
          {url: [{urlMatches: 'https://focusnote.com.cn/'}]}
        )

  // 缓存 与 localStorage 不同 需要在permission申明
  .storage
    .sync
      .set({key: value}, () => {}))
      .get(key, value => {})                                              // key/[key] 都行  res = {key: value}
      .remove(key, () => {})
      .clear(() => {})

    .local
      .set({key: value}, () => {})
      .get(key, res => {})                                                // key/[key] 都行  res = {key: value}
      .remove(key, () => {})
      .clear(() => {})

    .onChanged
      .addListener((changes, namespace) => {})
  
  .tabs
    .query
      ({}, tabs => {})                                                  // 获取所有窗口数组对象
      ({active: ture, currentWindow: true}, tabs => {})                 // 获取当前窗口对象

    .create
      ({url: newUrl})                                                   // 以newUrl打开新窗口
    .onCreated()

    .update
      (tabId, {url: newUrl})                                            // 在当前窗口打开newUrl,tabId为当前窗口id
    .onUpdated()

    // 通过编程方式注入到content script
    .executeScript
      (tabId, {code: 'window.alert('123')'})                            // 向当前窗口content script注入
      (tabId, {file: 'index.js'})                                       // 向当前窗口content script注入js文件

    .connect(tabId, {name: 'key'})                                      // 指定tab长连接通信
    .sendMessage                                                        // 用于页面通信

  .pageAction
    .show(tabId, () => {})                                                // 根据窗口id显示
    .hide(tabId, () => {})                                                // 根据窗口id隐藏
    .setTitle({tabId: tabId, title: '123'}, () => {})                     // 根据窗口id设置popup标题
    .getTitle({tabId: tabId}, () => {})                                   // 根据窗口id获取popup标题
    .setIcon({tabId: tabId, icon: './a.png'}, () => {})                   // 根据窗口id设置图标(猜的)
    .setPopup(tabId: tabId, popup: './pop.index'}, () => {})              // 根据窗口id设置popup页面
    .getPopup(tabId: tabId}, () => {})                                    // 根据窗口id获取popup页面路径

  // 端口
  .Port
    .onDisconnect                                                         // 监听关闭
      (() => {})

    .disconnect()                                                         // 手动关闭端口

  .downloads                                                              // 下载模块 需在permission申明
    .download({ url: url }, res => {})                                    // 下载
    .search({}, res => {})                                                // 搜索可下载列表 {} 增加搜索条件
    .pause(downloadId, res => {})                                         // 暂停
    .resume(downloadId, res => {})                                        // 恢复
    .cancel(downloadId, res => {})                                        // 取消

  .history                                                                // 浏览器历史
    .search({text: ''}, res => {})
    .getVisits({url: ''}, res => {})                                      // 检索访问信息
    .addUrl({url: ''}, res => {})                                         // 向历史记录添加
    .deleteUrl({url: ''}, res => {})                                      // 删除历史记录
    .deleteRange(                                                         // 删除改时间范围内的历史记录
      {startTime: Date.now() - 86400, endTime: Date.now},
      res => {}
    )
    .deleteAll(() => {})                                                  // 清空历史记录


popup.js / background.js

popup.js / background.js 可用 api (通过控制台打印获取)

chrome
  .app
  .bookmarks
  .browserAction
  .commands
  .contextMenu
  .declarativeContent
  .downloads
  .extension
  .history
  .i18n
  .loadTimes
  .management
  .permissions
  .runtime
  .storage
  .tabs
  .windows

contentScript

content script 可用 api

chrome
  .i18n
  .loadTimes
  .storage
  .extension
  .runtime
    .connect
    .getManifest
    .getURL                                                               // 获取扩展资源
    .id
    .onConnect
    .onMessage
    .sendMessage


manifest.json

{
  "name": "FocusNote",
  "version": "0.0.1",
  "manifest_version": 2,
  "description": "description",
  "icons": {
    "16": "image/focusnoteTest.png",
    "32": "image/focusnoteTest.png",
    "48": "image/focusnoteTest.png",
    "128": "image/focusnoteTest.png"
  },
  "default_locale": "zh_CN",
  "browser_action": {                                                     // browser_action 任何页面都能够使用扩展程序 page_action 指定页面显示 两者不能同时存在 两者配置项相同
    "default_title": "FocusNote",
    "default_icon": {
      "16": "image/focusnoteTest.png",
      "32": "image/focusnoteTest.png",
      "48": "image/focusnoteTest.png",
      "128": "image/focusnoteTest.png"
    },
    "default_popup": "popup/popup.html"
  },
  "options_ui": {                                                         // 扩展程序选项 chrome://extensions
    "page": "option/option.html",
    "open_in_tab": false
  },
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "content_scripts": [                                                    // 与页面共享window dom等等
    {
      "js": ["script/index.js"],
      "matches": [
        "http://*/*",
        "https://*/*"
      ],
      "run_at": "document_start"
    }
  ],
  "permissions": [
    "http://*/*",
    "https://*/*",
    "activeTab",                                                          // 使用chrome.tabs
    "contextMenus",                                                       // 右键菜单
    "storage",                                                            // 存储
    "declarativeContent",                                                 // 定义规则
    "bookmarks",                                                          // 书签
    "downloads",                                                          // 下载
    "history"                                                             // 浏览器历史
  ],
  "optional_permissions": [                                               // 提供给用户选择是否授权
    "tabs", "https://www.google.com/"
  ],
  "commands": {                                                           // 快捷键
    "flip-tabs-forward": {
      "suggested_key": {
        "default": "Ctrl+Shift+Right",
        "mac": "Command+Shift+Right"
      },
      "description": "Flip tabs forward"
    }
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值