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/23 11:30:50

RK3588语音AI部署终极指南:算子兼容性深度优化与实战解决方案

RK3588语音AI部署终极指南&#xff1a;算子兼容性深度优化与实战解决方案 【免费下载链接】sherpa-onnx k2-fsa/sherpa-onnx: Sherpa-ONNX 项目与 ONNX 格式模型的处理有关&#xff0c;可能涉及将语音识别或者其他领域的模型转换为 ONNX 格式&#xff0c;并进行优化和部署。 …

作者头像 李华
网站建设 2026/6/23 18:04:55

EmotiVoice语音好奇感模拟促进知识探索

EmotiVoice语音好奇感模拟促进知识探索 在AI助手越来越频繁地出现在我们生活中的今天&#xff0c;一个明显的问题浮出水面&#xff1a;为什么大多数语音交互仍然让人感觉“冷冰冰”&#xff1f;无论是车载导航的一板一眼&#xff0c;还是智能音箱千篇一律的回答&#xff0c;用户…

作者头像 李华
网站建设 2026/6/23 19:28:30

Abaqus轮轨瞬态动力学分析:从模型搭建到inp文件生成

Abaqus轮轨瞬态动力学分析。 考虑簧上质量-全轮对-轨道的轮轨瞬态滚动显式动力学模型。 考虑计算区域网格细化&#xff0c;提供inp文件。在铁路工程领域&#xff0c;轮轨瞬态动力学分析对于研究列车运行时轮轨之间的相互作用至关重要。今天咱就唠唠基于Abaqus软件的轮轨瞬态动力…

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

使用Playwright集成亮数据IP代理获取AI热点

使用Playwright集成亮数据IP代理获取AI热点根据下方链接体验亮数据&#xff1a;https://www.bright.cn/integration/playwright/?utm_sourcebrand&utm_campaignbrnd-mkt_cn_csdn_zhouzhou202512&promobright30

作者头像 李华
网站建设 2026/6/23 19:35:52

探索工程模拟与分析的多元世界:从轨道到建筑

ABAQUS动&#xff0c;静力学模型&#xff1b;车辆-轨道耦合动力学&#xff1b;钢轨不平顺程序&#xff1b;批量非线性弹簧&#xff1b;单向弹簧(收拉不受压或受压不受拉)&#xff0c;温度耦合等。 轨道检算(超高&#xff0c;超限&#xff0c;出报告)&#xff1b;土木建筑有限元…

作者头像 李华
网站建设 2026/6/23 22:37:15

Cuberite服务器日志分析完全指南:从入门到实战

Cuberite作为一款轻量级、快速且可扩展的Minecraft游戏服务器&#xff0c;其日志系统是诊断服务器健康状况的"诊断报告"。通过系统性的日志分析&#xff0c;管理员能够快速识别性能瓶颈、插件冲突和系统错误&#xff0c;确保玩家获得流畅的游戏体验。本指南将从基础概…

作者头像 李华