如何修复Edge扩展中Content Security Policy directive 'script-src 'self''错误?
修复JurSearch Edge扩展的问题
问题根源
- 内联脚本违反CSP:Manifest V3严格禁止内联事件处理(如
onclick、onsubmit),这直接导致提交按钮的点击事件被浏览器拦截,触发你看到的CSP错误。 - Service Worker无法访问DOM:你把
OpenSite函数放在background.js(Service Worker)里,但Service Worker没有页面DOM上下文,根本无法调用document.getElementById获取输入框的值,这也是按钮无反应的核心原因。
具体修复步骤
1. 新建popup/popup.js文件
在popup目录下创建该文件,专门处理popup的交互逻辑:
document.addEventListener('DOMContentLoaded', () => { const form = document.getElementById('form'); form.addEventListener('submit', (e) => { e.preventDefault(); // 阻止表单默认提交行为 const gesetz = document.getElementById('Gesetz').value.trim(); const norm = document.getElementById('Norm').value.trim(); if (gesetz && norm) { const site = `https://dejure.org/gesetze/${gesetz}/${norm}.html`; // 用扩展标准API打开新标签 chrome.tabs.create({ url: site }); } }); });
2. 修改popup/popup.html
移除所有内联事件,引入新建的外部脚本:
<html lang="de"> <head> <meta charset="UTF-8" /> <title>Search</title> </head> <body> <div> <form id="form"> <label for="Gesetz">Legal Code:</label> <input type="text" id="Gesetz" name="Gesetz"/><br><br> <label for="Norm">§/Art.:</label> <input type="text" id="Norm" name="Norm"><br><br> <input type="submit" value="Submit"/> </form> </div> <!-- 引入外部脚本 --> <script src="popup.js"></script> </body> </html>
3. 简化manifest.json
移除不需要的权限和后台配置(若没有其他后台逻辑):
{ "name": "JurSearch", "version": "0.0.0.1", "author": "FN", "manifest_version": 3, "description": "An extension to search the German laws.", "icons": { "16": "icons/fernglas.png" }, "action": { "default_popup": "popup/popup.html" }, "permissions": [ "tabs" ] }
4. 清理无用文件
如果没有其他后台功能需求,直接删除js/background.js文件即可。
修复逻辑说明
- 用外部脚本替代内联事件:完全符合Manifest V3的内容安全策略,避免脚本被浏览器拦截。
- 在popup上下文处理DOM:popup的JS直接运行在弹窗页面内,能正常访问输入框等DOM元素。
- 使用
chrome.tabs.create替代window.open:这是Edge/Chrome扩展打开新标签的标准API,比原生window.open更适配扩展环境,仅需tabs权限即可。
内容的提问来源于stack exchange,提问作者Fabian
相关产品推荐
相关产品推荐

