[关闭]
@forestsheep 2019-12-17T09:59:15.000000Z 字数 2042 阅读 396

Chrome扩展开发的简介与实战(7)

学习

图表版

存储的共享和消息传递

有三个区域并不是直接互通的,他们是

他们之间可以互通信息,但有一定的规则。

存储的共享

background内的共享自己的localstorage

backgound范畴的项目如果运用localstorage储存东西,他们都会存到一个地方。

以下这些地址前面的部分都相同。

chrome-extension://ccfbnhhlemoobofbfakkgpggmaocldlk/_generated_background_page.html

chrome-extension://ccfbnhhlemoobofbfakkgpggmaocldlk/option.html

chrome-extension://ccfbnhhlemoobofbfakkgpggmaocldlk/popup.html

localstorage

只要在相同的协议、相同的主机名、相同的端口下,就能读取/修改到同一份localStorage数据。

background和contentscript共享chrome.storage

前面已经讲过,chromestorage是改造过的localstorage,它在扩展内都是唯一的。

contentscript和origin web page共享自己的localstorage

假设我们对bozuman进行了注入,不管是原生的网页还是注入好的contentscript他们所属的地址都是:
https://bozuman.cybozu.com/
所以他们注定使用同一份localstorage

消息传递

background发消息给contentscript

Created with Raphaël 2.1.2backgroundbackgroundcontentscriptcontentscriptchrome.tabs.sendMessage()chrome.runtime.onMessage.addListener()sendResponse()handle response

contentscript发消息给background

Created with Raphaël 2.1.2contentscriptcontentscriptbackgroundbackgroundchrome.runtime.sendMessage()chrome.runtime.onMessage.addListener()sendResponse()handle response

originwebpage发消息给contentscript

Created with Raphaël 2.1.2originwebpageoriginwebpagecontentscriptcontentscriptwindow.postMessage()window.onmessage

研究

  1. contentscript传消息给originwebpage证实可以
  2. originwebpage发消息给background证实不行。

可以直接传递消息与否示意图

Created with Raphaël 2.1.2backgroundbackgroundcontentscriptcontentscriptorigin web pageorigin web page不可不可

不可直接传递的,可通过contentscript间接传递。

闹钟

https://developer.chrome.com/extensions/alarms

创建闹钟

  1. // 描述何时应触发闹钟。
  2. // 初始时间必须由when或delayInMinutes指定(但不能同时指定)。
  3. // 如果设置了periodInMinutes,则闹钟将在初始事件后每隔periodInMinutes分钟重复一次。
  4. // 如果没有为重复警报设置when或delayInMinutes,则将periodInMinutes用作delayInMinutes的默认值。
  5. let alarmInfo = {
  6. // when: Date.now(),
  7. delayInMinutes: 10,
  8. periodInMinutes: 1440
  9. }
  10. // 创建闹钟
  11. chrome.alarms.create("myAlarm", object alarmInfo)

设定闹钟行为

  1. chrome.alarms.onAlarm.addListener(function(alarm) {
  2. let delayms = getrandom(7)
  3. if (alarm.name === "myalarm") {
  4. // do something
  5. }
  6. })

练习

基础:
刷新扩展1分钟后,在background打印hello world

提高:
打开kintone某app一条记录1分钟后,把此记录详细内容存到background的localstorage上。(不是chrome.storage)

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注