9

I am writing a FireFox-Extension and want to load Data from Server. But when I try to initialize the XMLHttpRequest with:

var request = new XMLHttpRequest();

The error console says:

ReferenceError: XMLHttpRequest is not defined

Do I have to include something or why the XMLTttpRequest is not recognized?

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
SteMa
  • 2,945
  • 2
  • 24
  • 30
  • 1
    Is your code inside a JavaScript module? If so, have a look at https://developer.mozilla.org/En/XMLHttpRequest/Using_XMLHttpRequest#Using_XMLHttpRequest_from_JavaScript_modules_.2F_XPCOM.C2.A0components – Felix Kling Jan 02 '12 at 12:06
  • Hi Felix! I am using it in the main.js within a function. But when I do it your way the add-on builder says 'xpi file can not be copied' ... – SteMa Jan 02 '12 at 12:11
  • Are you using the new addon SDK? If so, I have not worked with it yet, so I cannot help you. Sorry. – Felix Kling Jan 02 '12 at 12:12
  • Yes the online addon builder at https://builder.addons.mozilla.org – SteMa Jan 02 '12 at 12:15

3 Answers3

11

The Add-on SDK (that you are using indirectly via the Add-on Builder) provides a request package that is essentially a wrapper around XMLHttpRequest, you should use it. From what I understand, you aren't given direct XMLHttpRequest access to prevent issues if the add-on is uninstalled/disabled while a request is being performed.

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
4

For using XMLHttpRequest constructor you should add the XPCOM component constructor:

const XMLHttpRequest  = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1", "nsIXMLHttpRequest");

and after:

// some code
var req = new XMLHttpRequest();
// some code

More info on MDN

Yurii Kovalenko
  • 419
  • 3
  • 10
1

It seems that Wladimir's answer is useful for most of such cases. But there is one more case.

I've found tris page trying to solve the problem with this error under Firefox 16. Strange, but I've never saw this error under Firefox 15.

I've got this error in content script on some pages. The script was injected at the start:

contentScriptWhen : "start",

It looks like in some cases window object was not initialized correctly. So, I've just changed script loading from start to end. It was possible in my case. The problem has gone...

I don't know why it appears, but know solution and hope that it will be useful for someone.