XMLHttpRequest Challenge with first Add-on


(Xalpha) #1

Hello Community!

I try to make my first Add-on. The Add-on will read data from a sensor over a webservice and prefill a form of a given site.

I have the following draft:

function myFunction() {
var request = new XMLHttpRequest();
// readData.php is the server-side script that communicates with WebJson and delivers the answer
request.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
request.setRequestHeader("Content-Type", "application/json");
request.addEventListener('load', function(event) {handleResponse(request)});
request.send('{"opcode":"read", "seq":0, "name":["Memory.TestInteger"]}');
}

function handleResponse(request)
{
var j = JSON.parse(request.responseText);
var i = j['id'];
document.querySelector('input[name = "q"]').value = i;
}

var myVar = setInterval(myFunction, 2000);

When I open the google page and add the code in the Console all two seconds the value “101” will be witten in the search form. Everything is perfect.

But wrapped into an Add-on as content_script it will not work. I have added several permission in the manifest.json. But the XMLHttpRequest is not working.

Is there someome with a good idea or similar observations?

Thank you.


(Niklas Gollenstede) #2

Have a look at the Network panel in the dev-tools.
This is a cross-origin request, so look for the access-control-allow-* headers on the OPTIONS preflight request.
The origin of the request might be your extensions origin, and the server might not handle that correctly.


(Xalpha) #3

That is exactly the thing I’m struggling with. When I use the script from the console the requests will be send and the answers are good:

access-control-allow-credentials true
access-control-allow-headers content-type
access-control-allow-methods GET,HEAD,PUT,PATCH,POST,DELETE
access-control-allow-origin https://www.google.de

When I try it as Add-on even the requests are not visible on the network panel. But a breakpoint at the request will stop every two seconds as expected. I don’t get any error or warning.

And the permissions are wide open:

 "permissions": [
        "<all_urls>",
        "storage",
        "cookies",
        "webNavigation",
        "webRequest",
        "tabs"
    ]

(Niklas Gollenstede) #4

Ok, then maybe try this:

window.timer = setInterval(async () => { try {
const data = (await (await window.unsafeWindow.fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({ opcode: "read", seq: 0, name: [ "Memory.TestInteger", ], }),
})).json());
document.querySelector('input[name = "q"]').value = data.id;
} catch (error) { console.error(error); } }, 2000);

The important part here is the unsafeWindow, to use the page version of fetch. I hope it works like this.