9
votes

I've looked high and low for an answer and I can't seem to find anything, Google's Docs seem incomplete to the matter of message sending to a Custom Receiver.

Also previous answers on StackOverflow seem to only be using the V1 Receiver API which don't seem to work with the V2 API.

Could anybody point me in the right direction to simply explain how to send a message from a Chrome Sender App to a Receiver using the V2 API?

2

2 Answers

20
votes

On the sender side you can send messages via the session object you get in the session listener:

session.sendMessage(namespace, message, onSuccess, onFailure);

https://developers.google.com/cast/docs/reference/chrome/chrome.cast.Session#sendMessage

On the receiver side you create a message bus and listen for incoming messages:

messageBus = castReceiverManager.getCastMessageBus(
    namespace,
    cast.receiver.CastMessageBus.MessageType.JSON
);

messageBus.onMessage = function(event) {
  var sender = event.senderId;
  var message = event.data;
};

https://developers.google.com/cast/docs/reference/receiver/cast.receiver.CastReceiverManager#getCastMessageBus https://developers.google.com/cast/docs/reference/receiver/cast.receiver.CastMessageBus

You can define the namespace yourself, but it must be the same in sender and receiver and start with urn:x-cast:

And it's important to define the correct Message type for the information you are going to send, but JSON is probably the most versatile.

You can also use the message bus to send messages back to the sender:

messageBus.send(senderId, message);

with a listener on the Sender side:

session.addMessageListener(namespace, function (ns, message) {

});

https://developers.google.com/cast/docs/reference/chrome/chrome.cast.Session#addMessageListener

I also have a very simple Chrome Sender/Custom Receiver sample up on Github with a complete implementation of sending messages: https://github.com/Scarygami/chromecast_experiments/tree/master/photocast

2
votes

As an update for @scarygami answer, if you need to do the same with CAF (API v3), this is how you listen for messages on the receiver side

const context = cast.framework.CastReceiverContext.getInstance();
context.addCustomMessageListener('urn:x-cast:<your-namespace>', event => {
    console.log('CustomMessage: ', event);
});

Here you can find the documentation: https://developers.google.com/cast/docs/reference/caf_receiver/cast.framework.CastReceiverContext#addCustomMessageListener