chrome 插件开发 background[4]

2020-03-24  本文已影响0人  proud2008

background指定的js文件是扩展被安装后会一直运行在浏览器中的程序,比如我们要保存一些扩展运行时的状态,缓存一些数据,或者绑定一些浏览器的事件等代码都可以放到这个js文件中。

// manifest.json
"background": {
    "scripts": [
      "libs/polyfill.min.js",
      "scripts/background.js"
    ]
  },
//background.js
'use strict';

chrome.runtime.onInstalled.addListener(details => {
  console.log('previousVersion', details.previousVersion);
});

console.log('\'Allo \'Allo! Event Page');

查看background的log

消息传递 官文档

//发送消息
 chrome.runtime.sendMessage({
        action: 'send',
        keyword: 'keyword value'
      }, function (response) {   //接收回调
        console.log(response);  //{state:'关键词填写成功!'}
      });

//监听扩展程序进程或内容脚本发送请求的请求
chrome.runtime.onMessage.addListener(
  function (request, sender, sendResponse) {
    if (request.action == 'send') {
      console.log('action',request,sender,sendResponse);
//  request {action: "send", keyword: "keyword value"}
 //sender  {id: "agkllkkjbhclhjnlebdbdagkagfgcecj", url: "chrome-extension://agkllkkjbhclhjnlebdbdagkagfgcecj/popup.html", origin: "chrome-extension://agkllkkjbhclhjnlebdbdagkagfgcecj"}
//sendResponse  ƒ () { [native code] }
      sendResponse({state:'关键词填写成功!'});
    }
  }
);
//manifest.json
 "permissions" : ["tabs", "activeTab"] //向浏览器申请的权限

  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {greeting: 'hello'}, function(response) {
      console.log(response.farewell);
    });
  });

//只有content-script中才能接收到,background是接收不到的
chrome.runtime.onMessage.addListener(//监听扩展程序进程或内容脚本发送请求的请求
  function (request, sender, sendResponse) {
    console.log('baidu',request, sender, sendResponse)
    sendResponse({state: '提交成功!'})
  })
//manifest.json
 "background": {
    "scripts": [
      "libs/polyfill.min.js",
      "scripts/background.js"
    ],
    "persistent": false
  }
//background.js
var count = 100; //会持续保存
//browser_action js页面
var bg = chrome.extension.getBackgroundPage();
bg.test();//test()是background中的一个方法
bg.count

长连接会话 Long-lived connections

//content script 
var port = chrome.runtime.connect({name: "knockknock"});
port.postMessage({joke: "Knock knock"});
port.onMessage.addListener(function(msg) {
  if (msg.question == "Who's there?")
    port.postMessage({answer: "Madame"});
  else if (msg.question == "Madame who?")
    port.postMessage({answer: "Madame... Bovary"});
});
//background script
chrome.runtime.onConnect.addListener(function(port) {
  console.assert(port.name == "knockknock");
  port.onMessage.addListener(function(msg) {
    if (msg.joke == "Knock knock")
      port.postMessage({question: "Who's there?"});
    else if (msg.answer == "Madame")
      port.postMessage({question: "Madame who?"});
    else if (msg.answer == "Madame... Bovary")
      port.postMessage({question: "I don't get it."});
  });
});
chrome.runtime
上一篇下一篇

猜你喜欢

热点阅读