【发布时间】:2026-02-08 04:45:01
【问题描述】:
在我的 Firefox WebExtensions 插件的内容脚本中有一个 XMLHttpRequest。 Q:为什么这个请求的状态总是0?
这是发出请求的 JavaScript 代码:
var query = "http://api.wolframalpha.com/v2/query?appid=[MY-APP-ID]&includepodid=Comparison&scanner=Unit&format=plaintext&input=1%20lm";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
console.log("onreadystatechange");
console.log(this);
if (this.readyState == 4 && this.status == 200)
{
onSuccess(this.responseText);
}
};
xhttp.open("GET", query, true);
xhttp.send();
如果我打印出每个 onreadystatechange 调用的请求结果,我会得到:
XMLHttpRequest { onreadystatechange: makeWolframRequest/xhttp.onreadystatechange(),
readyState: 1, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload,
responseURL: "", status: 0, statusText: "", responseType: "", response: "" }
XMLHttpRequest { onreadystatechange: makeWolframRequest/xhttp.onreadystatechange(),
readyState: 2, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload,
responseURL: "", status: 0, statusText: "", responseType: "", response: "" }
XMLHttpRequest { onreadystatechange: makeWolframRequest/xhttp.onreadystatechange(),
readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload,
responseURL: "", status: 0, statusText: "", responseType: "", response: "" }
我检查的内容:
- 内容脚本应该能够根据WebExtensions documentation进行跨域请求。
- 向“https://api.wolframalpha.com/”而不是“http://api.wolframalpha.com/”发出请求。
【问题讨论】:
-
readystatechange事件在 readystate 改变时触发,前三个发生在服务器响应之前,并且在响应之前你不能有状态码,这就是为什么它是0前三次,这也是我们检查readystate是否为4的原因,因为这表明收到了响应。问题可能不是前三个readystatechange调用的状态代码,而是其他问题。 -
根据我的实验,日志的 readystate 值是 1、2 和 4。我同意状态 0 对状态 1 和 2(在前两个日志中)有意义,但是readystate 4 和 status 0 是我担心的原因。
-
如果readystate为
4时status仍为0,则通常表示有其他问题。我没有应用程序 ID,无法对此进行测试,但我猜这是 CORS 错误。你是否为你的脚本设置了正确的权限,你不能通过请求正确的权限来进行跨源调用? -
@adeneo 如果您愿意,您可以发布一个答案供我选择,因为这确实是一个 CORS 问题。
标签: javascript ajax firefox-addon content-script firefox-addon-webextensions