Search code examples
javascriptgoogle-chromegoogle-chrome-extensionxmlhttprequest

Accessing XML response in Chrome Extension


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);
});

Solution

  • 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.