1

I am working on a very simple Chrome extension and am getting stuck while trying to make an XML request in order to access the data on current tab.

As is, I can get the extension to access the tab data, including the URL, when the extension icon is clicked. When it does so, it runs the background.js script. But I can only get as far as sending the request, never accessing the response. I have tried about as much as I can think of, but checking the .readyState attribute tells me the request is not getting done. Any thoughts?

For now I'm just trying to output to the console to show that I'm getting the data in a form in which I can use it, I'll flesh out what I'm going to do with it later.

Extension files below:

manifest.json

{"manifest_version": 2,
  "name": "ThisIsATest",
  "version": "0.1",
  "permissions" : [
    "activeTab"
  ],
  "background" : {
    "scripts" : ["background.js"],
    "persistent" : false
  },
  "browser_action" : {
    "default_title" : "Log Page Source Code"
  }
}

background.js

chrome.browserAction.onClicked.addListener(function(tab) {
    console.log('Getting URL: ' + tab.url);
    var xreq = new XMLHttpRequest();
    console.log(xreq.readyState);
    xreq.open('GET', tab.url);
    console.log(xreq.readyState);
    xreq.responseType = "text";
    xreq.send();
    console.log(xreq.response);
});
John Rossi
  • 68
  • 6
  • This is not how XHR is used. You need to use its `load` event or `readystatechange`. Look for examples, there are tons. – wOxxOm Aug 17 '20 at 18:22
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – hindmost Aug 17 '20 at 20:39

1 Answers1

1

You have to wait for the response, because it can take a while:

xreq = new XMLHttpRequest();
xreq.open('GET', tab.url);
xreq.onload = function () {
    console.log(xreq.response);
}
xreq.send();

You could also just use fetch: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch since it's way easier.

Nils Schwebel
  • 641
  • 4
  • 14