开发Chrome扩展时使用Microsoft Office API遇CSP错误的解决方法
解决Chrome扩展Manifest V3中加载Office API的CSP错误
问题场景
开发Chrome扩展(Manifest V3版本)时,尝试在JavaScript中调用Microsoft Office API,加载office.js时触发如下CSP错误:
Refused to load the script 'https://appsforoffice.microsoft.com/lib/1/hosted/office.js' because it violates the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval' 'inline-speculation-rules' http://localhost:* http://127.0.0.1:*". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
原Manifest.json的CSP配置片段:
"content_security_policy": { "extension_pages": "script-src 'self'; object-src 'self'; script-src-elem 'self' 'unsafe-inline' 'wasm-eval' https://appsforoffice.microsoft.com/lib/1/hosted/office.js;" }
可行解决方案(已消除CSP错误)
通过沙箱页面加载Office API,具体实现如下:
1. 创建沙箱页面相关文件
sandbox.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js" type="text/javascript"></script> <title>Sandbox Page</title> </head> <body> <div id="sandbox-content"> <p>This is a sandboxed page content.</p> </div> <script src="sandbox.js"></script> </body> </html>
sandbox.js
console.log("you are in sandbox.js"); Office.onReady(function (info) { if (info.host === Office.HostType.Excel) { // 执行Excel专属初始化操作(例如:使插件任务窗格样式匹配Excel主题) } if (info.platform === Office.PlatformType.PC) { // 对任务窗格做细微布局调整 } console.log(`Office.js is now ready in ${info.host} on ${info.platform}`); });
2. 主脚本嵌入沙箱页面
在主脚本mainscript.js中,通过创建iframe嵌入沙箱页面,从而调用Office API功能:
document.addEventListener("DOMContentLoaded", function () { const iframe = document.createElement("iframe"); iframe.src = chrome.runtime.getURL("sandbox.html"); iframe.id = "sandbox"; document.body.appendChild(iframe); });
3. 更新Manifest.json配置
修改Manifest.json的CSP和沙箱配置:
"content_security_policy": { "sandbox": "sandbox allow-scripts; script-src 'self' https://appsforoffice.microsoft.com" }, "sandbox": { "pages": ["sandbox.html"] },
内容的提问来源于stack exchange,提问作者Zaid Bhimala
相关产品推荐
相关产品推荐

