title: Listen to window events in an Angularjs service
body: <p>I want to listen to the window events in my AngularJS service so that I can broadcast them to my controllers.</p>
  
  <p>I have a Chrome extension which sends any message using <code>port.postMessage('Any Message');</code>.</p>
  
  <p>I want my angularjs service to listen to that message and send it to the controller using <code>$rootScope.$broadcast("Something occurred.");</code></p>
  
  <p>Inside my service, I am trying to do so with the following listener.</p>
  
  <pre><code>window.addEventListener('Any Message', function (event) {
      if (event.origin != window.location.origin) {
          return;
      }
      $rootScope.$broadcast("Something occurred.");
  });
  </code></pre>
  
  <p>I also tried <code>$window</code> but I don't know why the above code does not work. Also my IDE, jetbrains webstorms classify above code snippet as unreachable.</p>
  
  <p>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.</p>