Sending messages from Sender to Custom Receiver with Chromecast receiver API V2

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


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