news 2026/6/23 6:25:11

SharedArrayBuffer is not defined

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
SharedArrayBuffer is not defined

Uncaught ReferenceError: SharedArrayBuffer is not defined


这个错误通常是因为浏览器的安全策略限制导致的。


SharedArrayBuffer 错误原因

SharedArrayBuffer需要特殊的浏览器安全设置才能使用,主要是因为安全漏洞(如 Spectre 攻击)的原因,现代浏览器默认禁用了它。


跨源隔离(Cross-Origin Isolation)

要在浏览器中使用SharedArrayBuffer,必须启用跨源隔离。这需要在服务器响应头中设置以下两个头部:

Cross-Origin-Embedder-Policy: require-corp

Cross-Origin-Opener-Policy: same-origin


或更宽松的配置

Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: same-origin


使用本地服务器而非文件协议

不要直接双击 HTML 文件打开(file:// 协议),而是使用本地服务器。


本地开发时的快速解决方案

第一步:Chrome 浏览器禁用 Web 安全

启动 Chrome 时添加以下标志:

bash

chrome --disable-web-security --user-data-dir=/tmp/chrome-test

Windows系统上启动 Chrome 并添加标志的方法:

方法1:使用 CMD 命令行(最简单)
  1. Win + R,输入cmd,回车

  2. 在 CMD 中输入:


cmd

"C:\Program Files\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:\temp\chrome-test"

方法2:在 PowerShell 中正确的语法

powershell

& "C:\Program Files\Google\Chrome\Application\chrome.exe" "--disable-web-security" "--user-data-dir=C:\temp\chrome-test"

或者:

powershell

Start-Process "C:\Program Files\Google\Chrome\Application\chrome.exe" -ArgumentList "--disable-web-security", "--user-data-dir=C:\temp\chrome-test"

验证是否成功

启动后,你应该看到 Chrome 顶部的警告横幅:

text

您使用的是不受支持的命令行标记:--disable-web-security。稳定性和安全性会有所下降。


后续页面打开都在这个新弹出的窗口中进行测试


其他方式:创建快捷方式

  1. 右键点击 Chrome 快捷方式,选择"属性"

  2. 在"目标"字段的末尾添加:

    text

    --disable-web-security --user-data-dir="C:\temp\chrome-test"
  3. 完整的目标路径应该类似:

    text

    "C:\Program Files\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:\temp\chrome-test"
  4. 点击"应用",然后双击此快捷方式启动


或者使用 Chrome 扩展程序(推荐,但可能无法获取)

安装这些扩展可以绕过 CORS 限制:

  1. Allow CORS: Access-Control-Allow-Origin

    • Chrome Web Store 链接:https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf

    • 安装后,点击图标开启/关闭

  2. Moesif CORS

    • 功能更强大,可以自定义配置

    • 链接:https://chrome.google.com/webstore/detail/moesif-origin-cors-change/digfbfaphojjndkpccljibejjbppifbc


HTTPS要求

请注意,大多数浏览器要求使用HTTPS才能启用SharedArrayBuffer(localhost除外)。


即使禁用了 Web 安全,SharedArrayBuffer仍然需要特定的 HTTP 头部才能启用。

浏览器的警告横幅只是禁用了 CORS,但没有设置必要的 COOP/COEP 头部。


第二步:必须设置正确的响应头(使用本地服务器并设置头部)

1、使用 Node.js + Express

javascript

// server.js const express = require('express'); const app = express(); const path = require('path'); // 设置必需的头部 app.use((req, res, next) => { res.setHeader('Cross-Origin-Opener-Policy', 'same-origin'); res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp'); res.setHeader('Access-Control-Allow-Origin', '*'); next(); }); app.use(express.static('.')); app.listen(8080, () => { console.log('Server running at http://localhost:8080/'); console.log('Headers set: COOP=same-origin, COEP=require-corp'); });

运行:

bash

node server.js

安装 Express

# 临时使用淘宝镜像安装
npm install -g express --registry=https://registry.npmmirror.com

# 或者设置永久使用淘宝镜像
npm config set registry https://registry.npmmirror.com

# 验证配置
npm config get registry


2、使用纯 Node.js(无需额外安装 Express)

创建server.js

javascript

const http = require('http'); const fs = require('fs'); const path = require('path'); const server = http.createServer((req, res) => { console.log(`${req.method} ${req.url}`); // 设置必需的头部 res.setHeader('Cross-Origin-Opener-Policy', 'same-origin'); res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp'); res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); // 处理 OPTIONS 预检请求 if (req.method === 'OPTIONS') { res.writeHead(200); res.end(); return; } // 确定请求的文件路径 let filePath = '.' + req.url; if (filePath === './') { filePath = './worker.html'; // 默认加载你的 HTML 文件 } // 获取文件扩展名 const extname = path.extname(filePath); let contentType = 'text/html'; // 根据扩展名设置 Content-Type switch (extname) { case '.js': contentType = 'text/javascript'; break; case '.css': contentType = 'text/css'; break; case '.json': contentType = 'application/json'; break; case '.png': contentType = 'image/png'; break; case '.jpg': contentType = 'image/jpg'; break; case '.wasm': contentType = 'application/wasm'; break; } // 读取文件 fs.readFile(filePath, (error, content) => { if (error) { if (error.code === 'ENOENT') { // 文件不存在 fs.readFile('./404.html', (err, notFoundContent) => { if (err) { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('404 Not Found\n'); } else { res.writeHead(404, { 'Content-Type': 'text/html' }); res.end(notFoundContent, 'utf-8'); } }); } else { // 服务器错误 res.writeHead(500); res.end('Server Error: ' + error.code); } } else { // 成功响应 res.writeHead(200, { 'Content-Type': contentType, 'Content-Length': content.length }); res.end(content, 'utf-8'); } }); }); const port = 8080; server.listen(port, () => { console.log(`Server running at http://localhost:${port}`); console.log('Required headers are set:'); console.log(' Cross-Origin-Opener-Policy: same-origin'); console.log(' Cross-Origin-Embedder-Policy: require-corp'); console.log(' Access-Control-Allow-Origin: *'); console.log('\nOpen your browser to: http://localhost:8080/worker.html'); });

3、使用 Python(最简单,无需网络)

如果你安装了 Python3(WSL Ubuntu 通常自带):

bash

# 创建 Python 服务器脚本 cat > sab_server.py << 'EOF' import http.server import socketserver import os PORT = 8080 class SharedArrayBufferHandler(http.server.SimpleHTTPRequestHandler): def end_headers(self): # 设置 SharedArrayBuffer 必需的头部 self.send_header('Cross-Origin-Opener-Policy', 'same-origin') self.send_header('Cross-Origin-Embedder-Policy', 'require-corp') self.send_header('Access-Control-Allow-Origin', '*') super().end_headers() def log_message(self, format, *args): # 简化日志输出 print(f"[{self.log_date_time_string()}] {self.address_string()} - {format%args}") # 切换到脚本所在目录 script_dir = os.path.dirname(os.path.abspath(__file__)) os.chdir(script_dir) print("\n" + "="*50) print("🚀 SharedArrayBuffer Development Server") print("="*50) print(f"📡 URL: http://localhost:{PORT}") print(f"📁 Directory: {script_dir}") print("\n🔧 Headers configured:") print(" • Cross-Origin-Opener-Policy: same-origin") print(" • Cross-Origin-Embedder-Policy: require-corp") print(" • Access-Control-Allow-Origin: *") print("\n📄 Available HTML files:") for file in os.listdir('.'): if file.endswith('.html'): print(f" → http://localhost:{PORT}/{file}") print("\n" + "="*50) print("Press Ctrl+C to stop the server") print("="*50 + "\n") with socketserver.TCPServer(("", PORT), SharedArrayBufferHandler) as httpd: try: httpd.serve_forever() except KeyboardInterrupt: print("\n👋 Server stopped by user") EOF # 运行 Python 服务器 python3 sab_server.py

启动步骤

# 1. 进入你的项目目录 cd /mnt/d/code/jinqiu/myStudy # 2. 使用 Python 服务器(如果已安装 Python3) python3 server.py # 3. 或者使用 Node.js 服务器(如果已安装 Node.js) node server.js # 4. 打开浏览器访问 # http://localhost:8080/worker.html # 或 # http://localhost:8080/test-sab.html

验证是否成功

访问http://localhost:8080/worker.html后,按 F12 打开开发者工具,查看:

  1. Network 标签→ 点击你的文件 → 查看 Response Headers

  2. 应该能看到:

    • Cross-Origin-Opener-Policy: same-origin

    • Cross-Origin-Embedder-Policy: require-corp



建议方案:

使用Python 方案最简单,因为:

  1. WSL Ubuntu 自带 Python3

  2. 无需安装任何额外包

  3. 自动设置所需头部

直接运行:

cd /mnt/d/code/jinqiu/myStudy python3 sab_server.py

一步到位的解决方案

在终端中直接运行这个:

cd /mnt/d/code/jinqiu/myStudy && python3 -c " import http.server as hs, socketserver as ss, os, sys p=8080 class H(hs.SimpleHTTPRequestHandler): def end_headers(self): self.send_header('Cross-Origin-Opener-Policy','same-origin') self.send_header('Cross-Origin-Embedder-Policy','require-corp') self.send_header('Access-Control-Allow-Origin','*') super().end_headers() try: with ss.TCPServer(('',p),H) as s: print(f'✅ Server: http://localhost:{p}') print('🔧 Headers set for SharedArrayBuffer') [print(f'📄 http://localhost:{p}/{f}') for f in os.listdir('.') if f.endswith('.html')] print('🛑 Ctrl+C to stop') s.serve_forever() except: print(f'❌ Port {p} busy. Try: http://localhost:{p+1}') with ss.TCPServer(('',p+1),H) as s: print(f'✅ Now on: http://localhost:{p+1}') s.serve_forever() "

检测支持

在使用 SharedArrayBuffer 之前,最好先检测浏览器是否支持:

// 检查 SharedArrayBuffer 是否可用 if (typeof SharedArrayBuffer === 'undefined') { // 降级方案:使用普通 ArrayBuffer console.warn('SharedArrayBuffer is not available. Using fallback.'); // 创建一个简单的模拟(功能有限) window.SharedArrayBuffer = ArrayBuffer; // 或者根据你的需求调整代码逻辑 // 例如:使用 worker.postMessage 替代共享内存 }

完整示例

下面是一个使用 SharedArrayBuffer 的完整示例(需要适当的安全头部):

// 在代码中检测支持情况 function isSharedArrayBufferSupported() { try { if (typeof SharedArrayBuffer !== 'function') { return false; } // 测试是否可以实际创建 const sab = new SharedArrayBuffer(1); return sab instanceof SharedArrayBuffer; } catch (e) { return false; } } if (!isSharedArrayBufferSupported()) { // 提供降级方案或错误提示 console.error('SharedArrayBuffer is not supported in this environment'); // 提示用户更新浏览器或使用支持的浏览器 }
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/22 13:23:32

ComfyUI-SeedVR2视频超分模块:从入门到精通的全方位指南

ComfyUI-SeedVR2视频超分模块&#xff1a;从入门到精通的全方位指南 【免费下载链接】ComfyUI-SeedVR2_VideoUpscaler Non-Official SeedVR2 Vudeo Upscaler for ComfyUI 项目地址: https://gitcode.com/gh_mirrors/co/ComfyUI-SeedVR2_VideoUpscaler 在当今AI技术飞速发…

作者头像 李华
网站建设 2026/6/21 22:30:46

Venture项目管理工具终极指南:快速上手完整教程

Venture项目管理工具终极指南&#xff1a;快速上手完整教程 【免费下载链接】venture Venture allows you to create and manage complex, async workflows in your Laravel apps. 项目地址: https://gitcode.com/gh_mirrors/ve/venture Venture是一款专为Laravel应用设…

作者头像 李华
网站建设 2026/6/22 21:27:55

Codex多模型架构深度解析:构建高效AI开发工作流

Codex多模型架构深度解析&#xff1a;构建高效AI开发工作流 【免费下载链接】codex 为开发者打造的聊天驱动开发工具&#xff0c;能运行代码、操作文件并迭代。 项目地址: https://gitcode.com/GitHub_Trending/codex31/codex 在当今快速发展的AI领域&#xff0c;开发者…

作者头像 李华
网站建设 2026/6/22 18:50:22

CodeCombat终极指南:如何在游戏世界中快速掌握编程技能

CodeCombat终极指南&#xff1a;如何在游戏世界中快速掌握编程技能 【免费下载链接】codecombat Game for learning how to code. 项目地址: https://gitcode.com/gh_mirrors/co/codecombat 还在为枯燥的编程学习而烦恼吗&#xff1f;CodeCombat为你带来了革命性的解决方…

作者头像 李华
网站建设 2026/6/22 13:54:33

亲测好用:10个免费黑科技资源平台,获取资源不再花冤枉钱

当下获取资源的付费门槛似乎较为常见&#xff0c;想要获取实用的知识往往面临一定阻碍&#xff0c;实则是尚未发现合适的免费资源平台。以下整理了10个黑科技资源网站&#xff0c;可满足各种类型的资源获取需求。1. 发现AI一站式AI导航平台&#xff0c;发现AI整合了各类AI工具&…

作者头像 李华
网站建设 2026/6/18 21:59:13

如何快速掌握Redash数据可视化:从零到专家的完整指南

如何快速掌握Redash数据可视化&#xff1a;从零到专家的完整指南 【免费下载链接】redash getredash/redash: 一个基于 Python 的高性能数据可视化平台&#xff0c;提供了多种数据可视化和分析工具&#xff0c;适合用于实现数据可视化和分析。 项目地址: https://gitcode.com…

作者头像 李华