Search code examples
ajaxbrowser-extension

How do I make an AJAX request from a firefox browser extension?


I'm totally new to browser extensions. I've had some success making a simple extension that automatically changes webpage content, and now I want it to change that content after querying the server for a true or false value. I'm trying to do this with an AJAX request (pure javascript). For some reason, I can't get any information out of the PHP script on the server with which my browser extension is interacting.

Manifest:

{

  "manifest_version": 2,
  "name": "Truth Seeker",
  "version": "1.0",

  "description": "Returns true.",

  "icons": {
    "48": "icons/icon.png"
  },

  "content_scripts": [
    {
      "matches": ["*://*/*"],
      "js": ["script.js"]
    }
  ]

}

Script:

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);
}

The PHP file on the server just echos "true" at the moment. If I access that PHP script directly (by typing the URL into the browser), it will alert "is true". Why will it do it but no other pages will?


Solution

  • Well, I tore my hair out on this for a while, gave up on myself, asked a question, and then figured the answer out on my own within a few more minutes. To help anyone else in the future, I added this to the manifest:

      "permissions": [
        "webRequest",
        "<all_urls>"
      ],