在chrome扩展后台js中访问$http

access to $http in chrome extension background js

我的 angular 在我的 chrome 扩展的前端弹出窗口中工作正常,但我需要后台脚本来执行 ajax 请求,我什至无法开始思考如何我可以在那里得到 angular 的 $http。

具体来说,我将使用调用 chrome API "chrome.runtime.sendMessage".

的 ajax 结果进行响应

所以目前我的监听器已连接到 background.js

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

而我想要的是

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

这显然不起作用,即使 angular.js 在后台的清单文件中。

如何在此设置中使用 angular $http 对象? (我没有 background.js 的 html 页面)

要使用 $http,您必须在控制器、指令或 Angular 的服务中。

要按照您的方式进行操作,您可以创建一个 global variable,然后在控制器中您应该将 $http 分配给您创建的变量。

var $http2;

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

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

或者你可以用更简单的方式来做:

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()

要在不实例化任何控制器的情况下使用 $http 提供程序,请使用以下命令:

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