0

I have angular working fine for the front end popup of my chrome extension but I need the background script to do an ajax request and I cannot even begin to think how I can get angular's $http there.

Specifically I will be responding with the ajax result from a call to the chrome API "chrome.runtime.sendMessage".

So currently I have my listener wired up in the background.js

var someData="TESTDATA";
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    sendResponse(someData);
});

and what I want is

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
      $http({
    method: 'GET',
    url: "http://autocomplete.wunderground.com/' +
          'aq?query=" +
          'query'
  }).success(function(data) {
    sendResponse(data.RESULTS);
  }).error(function(err) {
    console.log(err);
  });
});

which obviously does not work even though angular.js is in the manifest file for the background.

How can I use the angular $http object in this setup? (I do not have an html page for the background.js)

4
  • Even though you said the angular is in your manifest file, could you please show us your manifest file? Commented Jun 5, 2015 at 16:45
  • 1
    Why do you need to use angular's $http? Why not just a standard XHR request? Commented Jun 5, 2015 at 21:52
  • @abraham simply consistency. Commented Jun 8, 2015 at 8:55
  • You may want to take a look at stackoverflow.com/a/24405235/934239 Commented Jun 24, 2015 at 16:35

2 Answers 2

1

To use $http, you must be within a controller, directive or Angular's service.

To do it the way you're doing, you can create a global variable, then within a controller you should assign $http to the variable you created.

var $http2;

myApp.controller('foo', ["$scope", "$http", function($scope, $http){
    $http2 = $http;
});

//Now you have access to: $http2({method:...})

Or you can do it in a simpler way:

var x = new XMLHttpRequest();
x.onload = function () {
    if(x.status == 200) {
        console.log(x.responseText);
        sendResponse(x.responseText);
    }
};
x.onerror = function(err) {
    console.log(err)
};
x.open('GET', 'http://autocomplete.wunderground.com/' + 'aq?query=' +  'query');
x.send()
Sign up to request clarification or add additional context in comments.

1 Comment

Yep trying to use angular as library was a really bad Idea I will just use standard AJAX
1

To use the $http provider without instantiating any controllers, use the following:

var $http = angular.injector(['ng']).get("$http");

1 Comment

Although I had settled on the AJAX route I did go back and try your suggestion and it works flawlessly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.