问题
I'm writing a chrome extension that consists of a background process and a popup. The background process continually makes ajax requests to get new data, and the popup displays the info.
In an extremely simplified way, the background.js process looks like this:
var Background = {
data: {},
poll: function() {
$.ajax({
url: 'some_url',
success: function(data) {
this.data = data;
chrome.extension.sendMessage('update');
}.bind(this)
});
},
startPolling: function() {
setInterval(this.poll.bind(this), 10000);
}
};
$(Background.startPolling.bind(Background));
This shoots of an ajax request every 10 seconds, gets some data back, and sets it to Background.data
. Again, this is very simplified. You can see the sendMessage
call in the success callback.
My popup.js looks something like this, also extremely simplified:
var Background = chrome.extension.getBackgroundPage().Background;
angular.module('App', [])
.controller('PopupCtrl', function PopupCtrl($scope) {
$scope.data = Background.data;
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request == 'update') {
console.log('update');
$scope.$apply();
}
});
});
And of course, popup.html looks something like:
<html ng-app="App" ng-csp>
<body ng-controller="PopupCtrl">
<p>{{data.title}}</p>
<p>{{data.body}}</p>
<p>{{data.date}}</p>
</body>
</html>
The message is definitely received, because I can see "update"
print to the console every 10 second interval. I also know that the data is being updated properly because if I close and reopen the popup, the new data is displayed correctly. So $scope.$apply()
is simply not doing anything.
How can I fix this?
来源:https://stackoverflow.com/questions/15595972/scope-apply-doesnt-do-anything-in-a-chrome-extension-popup