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

Firefox扩展中XMLHttpRequest未发送问题排查求助

我之前也碰到过Firefox扩展里XHR请求看似没发送的情况,结合你描述的细节——手动执行代码有效、服务器CORS已配置、函数正常调用,大概率是扩展权限或Firefox隐私机制在搞鬼,给你几个排查方向:

1. 检查扩展Manifest的权限配置

Firefox内容脚本默认受到严格的跨域限制,哪怕服务器开了Access-Control-Allow-Origin,如果扩展没在manifest.json里声明目标主机的权限,请求会被静默拦截。你需要添加对应的host权限:

// manifest.json
{
  "permissions": [
    "http://localhost:3621/*",
    "https://www.youtube.com/*" // 确保能访问YouTube页面元素
  ]
}
2. 给XHR添加错误监听,排查真实问题

你的代码里没有监听XHR的错误/状态事件,可能请求其实发送了但失败了,只是没输出日志。给request加上这些监听,就能看到到底是没发送还是有错误:

function sendTitle(title) {
 const request = new XMLHttpRequest();
 const url = `http://${hostname}/?song=${title}`;
 console.log(url);
 
 // 添加状态和错误监听
 request.onload = function() {
   console.log('请求响应状态:', this.status);
   console.log('响应内容:', this.responseText);
 };
 request.onerror = function() {
   console.error('请求失败:', this.statusText);
 };
 request.onabort = function() {
   console.warn('请求被中止');
 };
 
 request.open("GET", url);
 request.send(null);
 console.log("Request sent");
 console.log(request.url);
}

运行后看控制台的日志,就能明确是请求没发出,还是发出后被拒绝/报错。

3. 排查Firefox的增强跟踪保护

Firefox的增强跟踪保护(Enhanced Tracking Protection)可能会误判localhost的请求为跟踪行为,从而拦截。你可以:

  • 点击地址栏的盾牌图标,选择「关闭此网站的增强跟踪保护」,然后测试请求是否正常
  • 如果有效,可以在扩展里请求豁免,或者考虑改用fetch API(部分场景下fetch在隐私模式下的兼容性更好)
4. 改用Background脚本发起请求

内容脚本的环境限制较多,而Background脚本拥有更高的权限,不受内容脚本的跨域限制。你可以通过消息传递让Background脚本帮你发请求:

内容脚本(content script):

function sendTitle(title) {
  // 给background脚本发消息
  browser.runtime.sendMessage({
    action: "sendVideoTitle",
    title: encodeURIComponent(title)
  });
}

Background脚本(background.js):

const hostname = "localhost:3621";

browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === "sendVideoTitle") {
    const url = `http://${hostname}/?song=${message.title}`;
    fetch(url)
      .then(res => {
        console.log('请求成功,状态:', res.status);
        return res.text();
      })
      .then(data => console.log('服务器响应:', data))
      .catch(err => console.error('请求失败:', err));
  }
});

同时在manifest.json里声明Background脚本:

{
  "background": {
    "scripts": ["background.js"]
  }
}

这个方法几乎能绕过内容脚本的所有跨域和隐私限制,我之前用这个解决过类似的问题。

先从权限配置和错误监听开始排查,这两个是最常见的原因,应该能快速定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:27:35