Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 229
Truth Avatar asked Oct 19 '25 14:10

Truth


1 Answers

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>"
  ],
like image 51
Truth Avatar answered Oct 22 '25 04:10

Truth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!