如何从 firefox 浏览器扩展程序发出 AJAX 请求?
How do I make an AJAX request from a firefox browser extension?
我对浏览器扩展完全陌生。我已经成功地制作了一个自动更改网页内容的简单扩展,现在我希望它在查询服务器的 true 或 false 值后更改该内容。我正在尝试使用 AJAX 请求(纯 javascript)来执行此操作。出于某种原因,我无法从与我的浏览器扩展交互的服务器上的 PHP 脚本中获取任何信息。
清单:
{
"manifest_version": 2,
"name": "Truth Seeker",
"version": "1.0",
"description": "Returns true.",
"icons": {
"48": "icons/icon.png"
},
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["script.js"]
}
]
}
脚本:
theBool = false;
url = /* PHP URL HERE */;
string = "";
request(MakeOutput, url, string);
if(theBool == true){
alert("is true");
}
function MakeOutput(x){
if(x == "true"){
theBool = true;
}
}
function request(fix, url, string){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
fix(xhttp.responseText);
}
}
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(string);
}
服务器上的PHP文件此时只是回显"true"。如果我直接访问 PHP 脚本(通过在浏览器中键入 URL),它会警告 "is true"。为什么它会这样做而其他页面不会?
好吧,我为此焦头烂额了一会儿,放弃了自己,问了一个问题,然后在几分钟内自己想出了答案。为了将来帮助其他人,我将其添加到清单中:
"permissions": [
"webRequest",
"<all_urls>"
],
我对浏览器扩展完全陌生。我已经成功地制作了一个自动更改网页内容的简单扩展,现在我希望它在查询服务器的 true 或 false 值后更改该内容。我正在尝试使用 AJAX 请求(纯 javascript)来执行此操作。出于某种原因,我无法从与我的浏览器扩展交互的服务器上的 PHP 脚本中获取任何信息。
清单:
{
"manifest_version": 2,
"name": "Truth Seeker",
"version": "1.0",
"description": "Returns true.",
"icons": {
"48": "icons/icon.png"
},
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["script.js"]
}
]
}
脚本:
theBool = false;
url = /* PHP URL HERE */;
string = "";
request(MakeOutput, url, string);
if(theBool == true){
alert("is true");
}
function MakeOutput(x){
if(x == "true"){
theBool = true;
}
}
function request(fix, url, string){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
fix(xhttp.responseText);
}
}
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(string);
}
服务器上的PHP文件此时只是回显"true"。如果我直接访问 PHP 脚本(通过在浏览器中键入 URL),它会警告 "is true"。为什么它会这样做而其他页面不会?
好吧,我为此焦头烂额了一会儿,放弃了自己,问了一个问题,然后在几分钟内自己想出了答案。为了将来帮助其他人,我将其添加到清单中:
"permissions": [
"webRequest",
"<all_urls>"
],