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

Chrome扩展中WebAssembly模块编译错误问题咨询

Chrome扩展支持WebAssembly吗?当然!解决你遇到的编译错误

嘿,别慌——Chrome扩展完全支持WebAssembly,你碰到的CompileError: WebAssembly.compile(): Wasm code generation disallowed by embedder错误,根本原因是权限配置没到位,不是扩展不兼容Wasm。

为什么会出现这个错误?

Chrome为了安全,默认在扩展的上下文里禁用了"unsafe eval"类的操作,而WebAssembly的编译过程恰好属于这类操作范畴。所以必须显式在扩展清单里开启对应的权限,才能让浏览器允许生成Wasm代码。

解决步骤

  1. 更新扩展清单(manifest.json)
    你需要在permissions数组中添加"wasm-unsafe-eval"权限。如果是Manifest V3的扩展,配置示例如下:

    {
      "manifest_version": 3,
      "name": "你的扩展名称",
      "version": "1.0",
      "permissions": ["wasm-unsafe-eval"],
      "background": {
        "service_worker": "background.js"
      },
      "action": {
        "default_popup": "popup.html"
      },
      // 可选:如果需要让其他上下文(比如content script)访问Wasm文件,添加以下配置
      "web_accessible_resources": [
        {
          "resources": ["your-module.wasm"],
          "matches": ["<all_urls>"]
        }
      ]
    }
    

    Manifest V2的扩展配置类似,同样在permissions里加入"wasm-unsafe-eval"即可。

  2. 正确加载Wasm模块
    确保你从扩展内部加载Wasm文件(不要用外部URL,除非配置了对应的host_permissions),可以用chrome.runtime.getURL()获取正确的资源路径。示例代码(比如在background.js或popup的脚本里):

    async function initWasm() {
      try {
        // 获取扩展内Wasm文件的URL
        const wasmUrl = chrome.runtime.getURL('your-module.wasm');
        const response = await fetch(wasmUrl);
        const wasmBytes = await response.arrayBuffer();
        // 实例化Wasm模块
        const { instance } = await WebAssembly.instantiate(wasmBytes);
        // 调用Wasm导出的函数
        console.log('Wasm模块加载成功!示例调用:', instance.exports.yourFunction(10));
      } catch (error) {
        console.error('加载Wasm失败:', error);
      }
    }
    
    // 初始化加载
    initWasm();
    

额外注意事项

  • 如果你的扩展用的是Manifest V3的Service Worker作为背景页,同样需要配置wasm-unsafe-eval权限,Service Worker上下文的安全限制和普通页面一致。
  • 不要忘记把Wasm文件打包到扩展的目录里,确保它能被chrome.runtime.getURL()正确访问到。

只要配置好权限,不管是background还是popup页面,都能正常运行WebAssembly模块啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:28:53