Chrome Extensions V3 开发笔记

2025-03-15T14:03:00

Chrome 拓展开发

网页呼出Popup

类似在网页中需要插件登录、授权等操作的时候呼出Popup 来做进一步的操作。
需要通过拓展中的Content Script进行中转。

1.一个是网页(触发操作),通过window中的postMessage 发送一个操作如下。

document.getElementById('loginButton').addEventListener('click', () => {
  // 向 Content Script 发送消息
  window.postMessage({ type: 'EXTENSION_REQUEST', action: 'showAuthPopup' }, '*');
});
  1. 你需要创建一个 content-script 的插入脚本 在 manifest 文件中配置。
    例如
  "content_scripts": [
    {
      "matches": ["*://example.com/*"],
      "js": ["content.js"],
      "css": ["example.css"],
      "run_at": "document_idle"
    }
  ],

在文件中写入 以下内容,这里可以通过event.data拿到网页发送的所有数据,这里根据业务需求可以做过滤,也可以只作为一个转发功能拿到data后直接发送。

// content-script.js
window.addEventListener('message', (event) => {
  if (event.data.type === 'EXTENSION_REQUEST') {
    // 调用扩展的 API 向 Background Script 发送消息
    chrome.runtime.sendMessage({ action: 'showAuthPopup' }, (response) => {
      console.log('扩展响应:', response);
    });
  }
});
  1. 你需要创建一个 background-script 的worker脚本 在 manifest 文件中配置。

例如

  "background": {
    "service_worker": "/background.js"
  },

Background Script 中接收 Content Script 发来的内容,这里使用 chrome.action.openPopup(); 来呼出 Popup

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'showAuthPopup') {
    // 尝试打开扩展的 popup
    chrome.action.openPopup(); // 需要用户已配置图标或快捷键

    // 如果失败,提示用户手动操作
    if (!chrome.action.openPopup()) {
      chrome.notifications.create({
        type: 'basic',
        iconUrl: 'icon.png',
        title: '授权请求',
        message: '请单击插件图标进行授权登录'
      });
    }
    
    sendResponse({ success: true });
  }
});
当前页面是本站的「Baidu MIP」版。发表评论请点击:完整版 »