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

如何让Chrome扩展发送Origin为localhost的POST请求调用Ollama API

解决Chrome扩展向Ollama API发送请求时的Origin限制问题

Ollama API(一款本地运行大语言模型的服务)仅接受Origin为localhost的POST请求,但Chrome扩展代码运行在chrome-extension://[扩展ID]域名下,直接发送请求会因Origin不匹配被拒绝。以下是优雅的解决方案:

核心方案:用Chrome declarativeNetRequest API修改请求头

借助Chrome官方提供的declarativeNetRequest API,动态修改扩展发送的请求头,将Origin设置为http://localhost,无需额外代理,属于官方支持的合规方案。

可行代码实现

// 校验是否处于Chrome扩展环境
if (typeof chrome !== "undefined" && chrome.runtime && chrome.runtime.id) {
    // 构建并更新网络请求规则
    async function rebuildRules(domain) {
        const domains = [domain];
        /** @type {chrome.declarativeNetRequest.Rule[]} */
        const rules = [{
            id: 1,
            // 规则生效条件:请求目标为指定域名
            condition: {
                requestDomains: domains
            },
            // 执行动作:设置请求Origin头
            action: {
                type: 'modifyHeaders',
                requestHeaders: [{
                    header: 'origin',
                    operation: 'set',
                    value: `http://${domain}`,
                }],
            },
        }];
        // 先移除旧规则避免冲突,再添加新规则
        await chrome.declarativeNetRequest.updateDynamicRules({
            removeRuleIds: rules.map(r => r.id),
            addRules: rules,
        });
    }

    // 应用规则,将请求Origin设为localhost
    rebuildRules('localhost');
}

关键配置说明

  1. 权限声明:必须在扩展的manifest.json中添加对应权限,否则API无法生效:
    {
        "permissions": ["declarativeNetRequest"],
        "host_permissions": ["http://localhost:*/*"]
    }
    
  2. 原有请求代码无需修改:你之前的POST请求代码保持原样即可,网络规则会自动拦截并修改请求头:
    // 原POST请求代码,无需改动
    async function postRequest(data) {
      const URL = `${ollama_host}/api/generate`;
      try {
          const response = await fetch(URL, {
              method: 'POST',
              headers: {
                  'Content-Type': 'application/json',
              },
              body: JSON.stringify(data)
          });
          if (!response.ok) {
              const errorData = await response.json();
              document.getElementById('chatlog').innerHTML += `API返回错误:${errorData.message}`;
          }
          return response;
      } catch (error) {
        document.getElementById('chatlog').innerHTML += '请求失败: '+ error;
          throw error;
      }
    }
    
  3. Edge兼容性提示:当前代码在Edge侧边栏无法运行,推测是Edge对侧边栏扩展的网络规则有特殊限制,可尝试将扩展作为普通扩展在Edge中运行,或查阅Edge官方文档调整规则逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 06:27:41