Firefox WebExtension: Make XMLHttpRequest
Asked Answered
S

1

7

I'm making a Firefox WebExtension add-on. Here's what should happen:

  1. User clicks browser icon on ANY page.
  2. JavaScript is executed, collecting information from the page.
  3. Information is sent to my server using XMLHttpRequest

This is what my Chrome extension does. However, I cannot get this to work with the Firefox add-on. The JavaScript is injected and executed because I do see the alert(), which I have put at the end of the script. However, no call is made to my server. The Firefox debugger shows no attempted network activity, nor does it show any error.

Manifest:

{
  "manifest_version": 2,
  "name": "my_name",
  "version": "1.0",
  "description": "My description",
  "icons": {
    "48": "icons/my_icon.png"
  },
  "permissions": [
    "activeTab"
  ],
  "browser_action": {
    "default_icon": "icons/some_icon.png",
    "default_title": "My Name"
  },
  "background": {
    "scripts": ["background.js"]
  }
}

background.js:

browser.browserAction.onClicked.addListener(function(tab) {
    browser.tabs.executeScript(null, {file:"content_script.js"}); 
});

content_script.js:

var xmlHttp=new XMLHttpRequest();
xmlHttp.open("POST", "https://www.my_site.org",true);
var formData = new FormData();  
formData.append("my_var", "my_var");
xmlHttp.send(formData); 
alert("I do get here!");
Squatness answered 7/12, 2016 at 18:37 Comment(1)
You get to the alert because the lines above the alert are for asynchronous stuff. If the specific problem you're having is that the AJAX requests issued by the WebExtensions add-on are going out without "Origin" and/or "Referer" tags, then you'll be pleased that Firefox has fixed that problem as of current Developer Edition, version 52.0a2 (2016-12-12). Doesn't work on current Beta.Report
J
2

You need to add the URL to permissions in manifest.json

"permissions": [
    "activeTab",
    "*://developer.mozilla.org/*" <= URL
  ],
Jabe answered 8/12, 2016 at 9:3 Comment(1)
I'm having similar difficulties (on Firefox, but not Chromium), so I must be doing something wrong. Would "*://*.twitter.com/*", be a valid example of a URL pattern in the value of permissions?Report

© 2022 - 2024 — McMap. All rights reserved.