I want my web extension to make an AJAX call to the website which the user is currently looking at. I know that the current website has an endpoint available at /foo/bar?query=
.
Is there anything blocking me from using the fetch API or an XMLHttpRequest to contact this endpoint?
My attempts to use these methods just tell me that a server error has occurred, and nothing comes up in the network tab while I'm trying to debug my extension. I feel like there should be a WebExtensions API for this task, but I can't find one.
You can get an object describing the current tab the user is looking at using browser.tabs.getCurrent()
. This object has a property url
, which you can then use to make an XMLHttpRequest.
browser.tabs.getCurrent().then(currentTab => {
let xhr = new XMLHttpRequest();
xhr.open("GET", currentTab.url);
// ...
});
Edit:
As pointed out by Makyen, tabs.currentTab
is not actually what you want. Instead tabs.query
with active: true
should be used. Something like that should work:
browser.tabs.query({active: true, currentWindow: true}).then(tabs => {
let currentTab = tabs[0];
let xhr = new XMLHttpRequest();
xhr.open("GET", currentTab.url);
// ...
})
In order to make cross origin requests, you will need to get permission in your manifest.json
file:
{
...
"permissions": [
"tabs",
"<all_urls>"
],
...
}
<all_urls>
for instance will allow you to make http requests to any url.
You can read more here.