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

Chrome扩展开发报错求助:连接失败与CSP内联脚本拒绝

Chrome截图扩展报错修复方案

报错原因分析及修复

1. 连接建立失败错误(Unchecked runtime.lastError: Could not establish connection...)

  • 问题根源:
    • popup.html中存在两处重复发送take_screenshot消息的代码,逻辑冗余导致消息响应混乱;
    • 同时启用screenshot.js和background.js两个消息监听器,重复监听同一消息引发冲突;
    • chrome.tabs.captureVisibleTab属于后台权限API,放在临时生命周期的popup脚本中易触发异常,需统一由background脚本处理。
  • 修复方式:
    • 删除冗余的screenshot.js文件,仅保留background.js作为消息处理的后台脚本;
    • 清理popup.html中重复的消息发送逻辑,保留唯一的按钮点击触发代码。

2. 内容安全策略(CSP)报错

  • 问题根源:popup.html包含内联<script>代码,且manifest.json中配置的CSP哈希值与实际内联脚本不匹配,浏览器因此阻止内联脚本执行。
  • 修复方式:
    • 将所有内联脚本迁移到外部文件(如popup.js),彻底规避内联脚本的CSP限制;
    • 调整manifest.json的CSP配置,移除错误哈希值,保留合规的基础规则。

修复后的完整代码

manifest.json

{
    "manifest_version": 2,
    "name": "MySnap",
    "description": "Take a screenshot of a selected portion of the screen",
    "version": "1.0",
    "permissions": [
        "activeTab",
        "tabs"
    ],
    "browser_action": {
        "default_icon": "icon.png",
        "default_title": "MySnap",
        "default_popup": "popup.html"
    },
    "content_security_policy": "script-src 'self'; object-src 'self'"
}
<!DOCTYPE html>
<html>
<head>
    <title>MySnap</title>
</head>
<body>
    <h1>MySnap</h1>
    <button id="screenshot-button">Take Screenshot</button>
    <div id="screenshot-container"></div>
    <script src="popup.js"></script>
</body>
</html>
document.getElementById("screenshot-button").addEventListener("click", function() {
    chrome.runtime.sendMessage({message: "take_screenshot"}, function(response) {
        if (response && response.screenshotUrl) {
            const link = document.createElement("a");
            link.href = response.screenshotUrl;
            link.download = "screenshot.png";
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    });
});

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.message === "take_screenshot") {
        chrome.tabs.captureVisibleTab(null, {format: "png"}, function(screenshotUrl) {
            sendResponse({screenshotUrl: screenshotUrl});
        });
        return true; // 告知Chrome需保留连接以处理异步响应
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 07:20:28