Skip to content

Instantly share code, notes, and snippets.

@RavenHursT
Created April 7, 2014 00:12
Show Gist options
  • Save RavenHursT/10012913 to your computer and use it in GitHub Desktop.
Save RavenHursT/10012913 to your computer and use it in GitHub Desktop.
AngularJs messaging service/directive
.directive('postMessage', ['$window', 'postMessageService', function($window, postMessageService) {
return {
restrict: 'A',
controller: function($scope, $attrs, postMessageService) {
$scope.$on('outgoingMessage', function(evt, payload, targetOrigin, responseCallback) {
// console.log('Caught Message:');
// console.log(payload);
if ($scope.sender) {
var message = {
status: 200,
payload: payload
};
if(responseCallback){
var
timestamp = new Date().getTime(),
requestId = CryptoJS.SHA1(timestamp.toString()).toString(CryptoJS.enc.Base64);
if(!$scope.responseCallbacks){
$scope.responseCallbacks = [];
}
$scope.responseCallbacks[requestId] = responseCallback;
message.requestId = requestId;
}
message = JSON.stringify(message);
try {
$scope.sender.postMessage(message, targetOrigin);
} catch (err){
if(message.method && message.method != 'connect'){
console.error(err);
}
}
}
});
},
link: function postLink(scope, element, attrs) {
scope.sendMessageToService = function(e) {
if (e && e.data) {
var response = null;
scope.sender = e.source;
try {
response = angular.fromJson(e.data);
} catch (error) {
response = {
message: e.data
}
}
if(
response.requestId &&
scope.responseCallbacks &&
typeof scope.responseCallbacks[response.requestId] === 'function'
){
scope.responseCallbacks[response.requestId](response, e);
scope.responseCallbacks.splice(response.requestId, 1);
}
postMessageService.messages(response);
}
};
window.addEventListener('message', scope.sendMessageToService);
}
}
}])
.factory('postMessageService', ['$rootScope', function($rootScope) {
var $messages = [];
var api = {
messages: function(_message_) {
if (_message_) {
$messages.push(_message_);
$rootScope.$apply();
}
return $messages;
},
outgoing: function(message, targetOrigin, responseCallback) {
$rootScope.$broadcast('outgoingMessage', message, targetOrigin, responseCallback);
}
};
return api;
}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment