10

I want to listen to the window events in my AngularJS service so that I can broadcast them to my controllers.

I have a Chrome extension which sends any message using port.postMessage('Any Message');.

I want my angularjs service to listen to that message and send it to the controller using $rootScope.$broadcast("Something occurred.");

Inside my service, I am trying to do so with the following listener.

window.addEventListener('Any Message', function (event) {
    if (event.origin != window.location.origin) {
        return;
    }
    $rootScope.$broadcast("Something occurred.");
});

I also tried $window but I don't know why the above code does not work. Also my IDE, jetbrains webstorms classify above code snippet as unreachable.

Before this, I used the above code in a controller and it worked fine. I wasn't doing broadcast in controller. Now I want to move this to the service so that all controllers should be able to listen to it from service.

SamFast
  • 1,054
  • 2
  • 16
  • 31

4 Answers4

11

Here is working example I've made - with subscribing DOM event and broadcasting the event from service to controller: http://plnkr.co/edit/nk2aPt?p=preview

//this is service that creates subscription    
app.service('serviceName', function($window, $rootScope) {

      function subsFunc() {
        $window.addEventListener('click', function(e) {
          $rootScope.$broadcast('app.clickEvent', e);
        })
      }

      return {
        "subscribeMe": subsFunc      }
    });

//this will be in controller
  $rootScope.$on('app.clickEvent', function(a, b) {
    //a,b - event object details
  });
shershen
  • 9,875
  • 11
  • 39
  • 60
4

Something like this might help:

var app = angular.module('app', []);

app.run(["$window", "$rootScope", function($window, $rootScope) {

    $window.addEventListener('message', function(e) {

        $rootScope.$broadcast('message', e.data);
    });
} ]);
Rian
  • 1,243
  • 2
  • 17
  • 22
0

Do you inject that service somewhere? Services will run only if you really injects them.

Additionally, it's better to use $window instead of window, so you'll be able to mock it later in your tests.

AdirAmsalem
  • 176
  • 3
  • Yes, I do inject. Why does my IDE classifies it as unreachable? – SamFast Feb 07 '15 at 14:32
  • Don't know. I'd also recommend to check if you need to manually call $digest/$apply, as it is might be triggered outside of AngularJS. Anyway, if it doesn't works - upload a plunker/jsfiddle that reproduces this, it will be easier to help you this way. – AdirAmsalem Feb 07 '15 at 14:42
0

Problem:

"$window listener" listen multiple time. 

Example:

Consider , we wrote a listener code in Page B. My starting page is Page A.

I added an alert in listener code in Page B.

$window.addEventListener('message', function (e) { alert() }); 

Lets Go,

  • Page A >> Page B (alert count 1) Page B >> Page A >> Page B (alert count 2) Page B >> Page A >> Page B (alert count 3)
vishnu das
  • 11
  • 3