前期页面准备

manifest.json|
content_scripts : 浏览器里面使用的,和页面共享DOM,不共享JS

  1. content-scripts不能访问绝大部分chrome.xxx.api,除了下面这4种:
  2. chrome.extension(getURL , inIncognitoContext , lastError , onRequest , sendRequest)
  3.  chrome.i18n
  4. chrome.runtime(connect , getManifest , getURL , id , onConnect , onMessage , sendMessage)
  5. chrome.storage

background :     插件存在则存在, 随着浏览器的打开而打开,随着浏览器的关闭而关闭, 通常把需要一直运行的、启动就运行的、全局的代码放在background里面

  1. background的权限非常高,几乎可以调用所有的Chrome扩展API(除了devtools),而且它可以无限制跨域,也就是可以跨域访问任何网站而无需要求对方设置CORS。

popup页嵌入js : 仅仅该页面使用

 

{
  "manifest_version": 2,
  "name": "ones helps",
  "version": "1.0.0",
  "description": "pageAction演示",
  "icons": {
    "16": "img/icon.png",
    "48": "img/icon.png",
    "128": "img/icon.png"
  },
  "content_scripts": [
    {
      "matches": ["https://192.168.10.117/*"],  // 指定匹配的域名, 	<all_urls> 表示所有
      "js": ["./js/page.js"],
      "css": [],
      "run_at": "document_end" // 可选值: "document_start", "document_end", or "document_idle",最后一个表示页面空闲时,默认document_idle
    }
  ],
  "browser_action": {
    "default_icon": "img/icon.png",
    "default_popup": "popup.html",
    "default_title": "我是标题"
  },
  "background": {
    "scripts": ["./js/bj.js"],
    "persistent": false
  },
  "permissions": ["notifications","tabs"]
}

所有通信之前,发送方和接收方必须都存在,否则报错
 

01: background 和 content_scripts 的通信

  • 接收消息:chrome.runtime.onMessage.addListener
  • 发送消息:chrome.runtime.sendMessage
     

 content_scripts => page.js

let btn = document.querySelector('button');  // 页面DOM
btn.onclick = function () {
  sendMsg()
};

// 发送消息
function sendMsg() {
  chrome.runtime.sendMessage({ origin: 'pageJs' }, function (data) {
    // 接受返回信息
    console.log("🔷: page.js  send");
    console.log("🔷: page.js  sendBack", data);
    console.log('.....................');
  });
}



// 接受信息
function receiveMsg() {
  chrome.runtime.onMessage.addListener(function (data, sender, sendResponse) {
    console.log("👀: page.js  receive", data);
    console.log("👀: page.js  receiveFn");
    sendResponse(data);
    console.log('.....................');
  });
};
receiveMsg();

background => bj.js

// 接收到信息
function receiveMsg() {
  // data数据  sender发送方  sendResponse回调
  chrome.runtime.onMessage.addListener(function (data, sender, sendResponse) {
    console.log("😝: bj.js  receive", data);
    console.log("😝: bj.js  receiveFn");
    sendResponse(data)
    console.log('.....................');
    tabs();
  });
};
receiveMsg();


// 监测到新的tab
async function tabs() {
  const tabId = await getCurrentTabId();
  // 在背景页面发送消息,需要当前 tabID
  chrome.tabs.sendMessage(tabId, { name: 'bJs' }, function (data) {
    console.log("📌: bj.js  send");
    console.log("📌: bj.js  sendBack", data);
    console.log('.....................');
  });
};


// 获取当前 tab ID
function getCurrentTabId() {
  return new Promise((resolve, reject) => {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      resolve(tabs.length ? tabs[0].id : null)
    });
  })
};
// 监测打开了新的tab
chrome.tabs.onCreated.addListener(function (tab) {
  console.log('🎪: 监测打开了新', tab);
});

02: background 和 popup的通信

  • 接收消息:在background中: chrome.extension.getViews() 获取当前插件内每个运行页面的窗口数组([window, window])
  • 发送消息:在右上角弹出框中:chrome.extension.getBackgroundPage() 获取背景页面的窗口对象(window)

background => bj.js 在原来基础上增加一个通信函数

/**
 * 通信函数
 */
function backFun(...arg) {
  const allViews = chrome.extension.getViews()
  console.log(arg);
  console.log('chrome.extension.getViews():', allViews)
}

popup=> popup.js 

let btn = document.getElementById('submit');

// 可以获取到bj.js中设置的函数,
const background = chrome.extension.getBackgroundPage();

// 点击按钮
btn.onclick = function (e) {
  var name = document.getElementById('name').value;
  var password = document.getElementById('password').value;
  // sendMsg(name, password);
  background.backFun(name, password)
}

03: content_scripts 和 popup的通信

popup=> popup.js  

 

let btn = document.getElementById('submit');

// 点击按钮
btn.onclick = function (e) {
  var name = document.getElementById('name').value;
  var password = document.getElementById('password').value;
  tabs(name, password);
}

// 去链接,对应的tab标签页面
async function tabs(...arg) {
  const tabId = await getCurrentTabId();
  const connect = chrome.tabs.connect(tabId, { name: 'popup' }); // 和指定tabID建立链接,并设置信号名字
  // 发送信息
  connect.postMessage(arg);

  // 接受返回信息
  connect.onMessage.addListener(mess => {
    console.log(mess)
  })
};


// 获取当前 tab ID
function getCurrentTabId() {
  return new Promise((resolve, reject) => {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      resolve(tabs.length ? tabs[0].id : null)
    });
  })
};


 content_scripts => page.js

// 监听链接
chrome.runtime.onConnect.addListener(res => {
  if (res.name == "popup") {
    res.onMessage.addListener(mes => {
      console.log('🥓: popup.js receive', mes);
      res.postMessage('📣: popup.js receiveBack')
    });
  }
});

弹出框只要点击插件才能弹出,而当你操作页面的时候,插件弹框又会消失…消失之后,弹框的.js等都会销毁…所以,可以向background通信,然后点击弹出之后,弹出框和background通信,或者弹出之后直接向content_scripts通信

 04: content_scripts 和 popup的通信也可以通过另外方式传递

popup.js

// 点击按钮
btn.onclick = function (e) {
  var name = document.getElementById('name').value;
  var password = document.getElementById('password').value;
  tabs(name, password);
}

// 去链接,对应的tab标签页面
async function tabs(...arg) {
  const tabId = await getCurrentTabId();
  // 页面发送消息,需要当前 tabID
  chrome.tabs.sendMessage(tabId, { name: 'bJs' }, function (data) {
    console.log("📌: bj.js  send");
    console.log("📌: bj.js  sendBack", data);
    console.log('.....................');
  });
  
};

// 获取当前 tab ID
function getCurrentTabId() {
  return new Promise((resolve, reject) => {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      resolve(tabs.length ? tabs[0].id : null)
    });
  })
};

page.js

 chrome.runtime.onMessage.addListener(function (data, sender, sendResponse) {
    console.log("👀: page.js  receive", data);
    console.log("👀: page.js  receiveFn");
    sendResponse(data);
    console.log('.....................');
  });

另外还可以使用以下方式,page 和 bj , contentscript和 bj通讯 

  • 接收消息:chrome.runtime.onMessage.addListener
  • 发送消息:chrome.runtime.sendMessage


来源: 谷歌浏览器插件content_scripts、background、popup之间的通信_gqkmiss的博客-CSDN博客_content_scripts

Chrome浏览器插件(扩展)开发全攻略_丨匿名用户丨的博客-CSDN博客_chrome插件开发 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐