You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome扩展Manifest V3中如何在后台弹窗展示服务器返回结果?

在Chrome Manifest V3中实现后台结果弹窗展示的解决方案

你之前尝试消息通信失败的核心原因是:创建弹窗后立即发送消息时,popup2.html的脚本还未加载完成,消息监听器尚未注册,导致无法接收消息。以下是三种可行的实现方案:

方案一:使用Chrome存储API临时存数(推荐)

通过chrome.storage.local临时存储分析结果,弹窗加载完成后读取并展示。

1. 修改background.js

fetch(url, {
  method: "POST",
  body: formData
})
.then(response => response.json())
.then(data => {
  console.log(data); 
  // 将分析结果存入本地存储
  chrome.storage.local.set({analysisResult: data}, () => {
    // 存储完成后创建弹窗
    chrome.windows.create({
      focused: true,
      width: 400,
      height: 400,
      type: 'popup',
      url: 'popup2.html',
      top: 0,
      left: 0
    }).catch(error => {
      console.error('创建窗口失败: ', error);
    });
  });
})
.catch(error => {
  console.error('请求JSON失败: ', error);
});

2. 编写popup2.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>分析结果</title>
  <style>
    body { padding: 20px; font-family: Arial, sans-serif; }
    h1 { font-size: 18px; margin-bottom: 15px; }
    #results { line-height: 1.6; }
  </style>
</head>
<body>
  <h1 id="title"></h1>
  <div id="results"></div>
  <script src="popup2.js"></script>
</body>
</html>

3. 修改popup2.js

document.addEventListener('DOMContentLoaded', () => {
  chrome.storage.local.get('analysisResult', (result) => {
    if (result.analysisResult) {
      const data = result.analysisResult;
      const title = `Results of ${data.filename}`;
      const results = `File ${data.filename} has ${data.similarity} similarity with ${data.file}`;
      
      document.getElementById('title').textContent = title;
      document.getElementById('results').textContent = results;
      
      // 用完数据后删除,避免占用存储
      chrome.storage.local.remove('analysisResult');
    }
  });
});

方案二:等待弹窗加载完成后发送消息

通过监听弹窗标签的加载状态,确保页面完全加载后再发送消息。

修改background.js

fetch(url, {
  method: "POST",
  body: formData
})
.then(response => response.json())
.then(data => {
  console.log(data); 
  chrome.windows.create({
    focused: true,
    width: 400,
    height: 400,
    type: 'popup',
    url: 'popup2.html',
    top: 0,
    left: 0
  }, (window) => {
    const tabId = window.tabs[0].id;
    // 监听标签加载完成事件
    const loadListener = (tabIdUpdated, changeInfo) => {
      if (tabIdUpdated === tabId && changeInfo.status === 'complete') {
        // 发送分析结果
        chrome.tabs.sendMessage(tabId, {
          action: 'setData',
          data: data
        });
        // 移除监听器,避免重复触发
        chrome.tabs.onUpdated.removeListener(loadListener);
      }
    };
    chrome.tabs.onUpdated.addListener(loadListener);
  }).catch(error => {
    console.error('创建窗口失败: ', error);
  });
})
.catch(error => {
  console.error('请求JSON失败: ', error);
});

修改popup2.js

document.addEventListener('DOMContentLoaded', () => {
  chrome.runtime.onMessage.addListener((msg, sender) => {
    if (msg.action === 'setData') {
      const data = msg.data;
      const title = `Results of ${data.filename}`;
      const results = `File ${data.filename} has ${data.similarity} similarity with ${data.file}`;
      
      document.getElementById('title').textContent = title;
      document.getElementById('results').textContent = results;
    }
  });
});

方案三:通过URL参数传递数据(适合小数据量)

将分析结果编码后作为URL参数传递给弹窗页面。

修改background.js

fetch(url, {
  method: "POST",
  body: formData
})
.then(response => response.json())
.then(data => {
  console.log(data); 
  // 将数据转为URL安全的字符串
  const encodedData = encodeURIComponent(JSON.stringify(data));
  chrome.windows.create({
    focused: true,
    width: 400,
    height: 400,
    type: 'popup',
    url: `popup2.html?data=${encodedData}`,
    top: 0,
    left: 0
  }).catch(error => {
    console.error('创建窗口失败: ', error);
  });
})
.catch(error => {
  console.error('请求JSON失败: ', error);
});

修改popup2.js

document.addEventListener('DOMContentLoaded', () => {
  // 解析URL参数
  const urlParams = new URLSearchParams(window.location.search);
  const encodedData = urlParams.get('data');
  if (encodedData) {
    const data = JSON.parse(decodeURIComponent(encodedData));
    const title = `Results of ${data.filename}`;
    const results = `File ${data.filename} has ${data.similarity} similarity with ${data.file}`;
    
    document.getElementById('title').textContent = title;
    document.getElementById('results').textContent = results;
  }
});

必要的Manifest配置

确保在manifest.json中添加所需权限:

{
  "manifest_version": 3,
  "permissions": ["storage", "tabs"],
  "background": {
    "service_worker": "background.js"
  }
}

内容的提问来源于stack exchange,提问作者josecarlosgar23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 03:55:32