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

Transformer.js在Next.js客户端示例中JSON解析失败(仅Brave浏览器)

Brave浏览器下Hugging Face客户端推理示例的JSON解析错误修复

问题描述

  • 在**Brave 1.61.101(基于Chromium 120.0.6099.71 x86_64)**开发模式运行Hugging Face Next.js客户端推理示例时,触发JSON解析错误,文本分类功能完全失效
  • 相同未修改的教程代码,在**Chrome 120.0.6099.62(x86_64)**中可正常运行

错误截图:
JSON解析错误

涉事代码(未修改的TransformerWorker.js)

import { pipeline, env } from "@xenova/transformers";

// Skip local model check and cache
env.allowLocalModels = false;

// Use the Singleton pattern to enable lazy construction of the pipeline.
class PipelineSingleton {
    static task = 'text-classification';
    static model = 'Xenova/distilbert-base-uncased-finetuned-sst-2-english';
    static instance = null;

    static async getInstance(progress_callback = null) {
        if (this.instance === null) {
            this.instance = pipeline(this.task, this.model, { progress_callback });
        }
        return this.instance;
    }
}

// Listen for messages from the main thread
self.addEventListener('message', async (event) => {
    // Retrieve the classification pipeline. When called for the first time,
    // this will load the pipeline and save it for future use.
    let classifier = await PipelineSingleton.getInstance(x => {
        // We also add a progress callback to the pipeline so that we can
        // track model loading.
        self.postMessage(x);
    });

    // Actually perform the classification
    let output = await classifier(event.data.text);

    // Send the output back to the main thread
    self.postMessage({
        status: 'complete',
        output: output,
    });
});

解决方法

  • 调整Brave Shields防护设置:点击地址栏右侧的Shields图标,将"跨站脚本拦截"设为"允许",或直接关闭Shields测试。Brave的隐私防护可能拦截了模型加载过程中的JSON数据传输,导致解析失败。
  • 显式序列化消息数据:Brave对Worker postMessage的序列化规则更严格,可在发送结果前将output转为JSON字符串,主线程接收时再解析。
    修改Worker中发送结果的代码:
    self.postMessage({
        status: 'complete',
        output: JSON.stringify(output),
    });
    
    主线程接收逻辑调整:
    worker.onmessage = (e) => {
        if (e.data.status === 'complete') {
            const output = JSON.parse(e.data.output);
            // 后续结果处理逻辑
        }
    };
    
  • 更新Brave至最新版本:当前Brave的Chromium版本比测试的Chrome略高,可能存在兼容性bug,更新浏览器后大概率能修复JSON解析相关问题。
  • 关闭高级隐私增强功能:暂时禁用"指纹防护""跟踪保护"等设置,部分严格防护规则可能干扰了Transformer.js的正常数据交互。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 13:21:21