Skip to content

Instantly share code, notes, and snippets.

@TylerFisher
Last active March 22, 2020 11:26
Show Gist options
  • Save TylerFisher/9415aa0e75040f13028d to your computer and use it in GitHub Desktop.
Save TylerFisher/9415aa0e75040f13028d to your computer and use it in GitHub Desktop.
A basic library and example usage for JavaScript-based Chromecast apps, developed by NPR Visuals for elections.npr.org.
var IS_CAST_RECEIVER = (window.location.search.indexOf('chromecast') >= 0);
var is_casting = false;
var $castStart = null;
var $castStop = null;
var $chromecastScreen = null;
var $audioPlay = null;
var $audioPause = null;
/*
* Fire this if user has Chromecast extension
*/
window['__onGCastApiAvailable'] = function(loaded, errorInfo) {
// We need the DOM here, so don't fire until it's ready.
$(function() {
// Don't init sender if in receiver mode
if (IS_CAST_RECEIVER) {
return;
}
// init sender and setup callback functions
CHROMECAST_SENDER.setup(onCastReady, onCastStarted, onCastStopped);
});
}
/*
* A cast device is available.
*/
var onCastReady = function() {
$castStart.show();
}
/*
* A cast session started.
*/
var onCastStarted = function() {
// show what you want to appear on the casting device here
$chromecastScreen.show();
// set a global variable to make special casing code on the sender easier
is_casting = true;
$castStart.hide();
$castStop.show();
}
/*
* A cast session stopped.
*/
var onCastStopped = function() {
// revert back to a one-screen experience
$chromecastScreen.hide();
STACK.start();
is_casting = false;
$castStop.hide();
$castStart.show();
}
/*
* Begin chromecasting.
*/
var onCastStartClick = function(e) {
e.preventDefault();
// fire the Chromecast-specific start function, which will fire the callback defined above
CHROMECAST_SENDER.startCasting();
}
/*
* Stop chromecasting.
*/
var onCastStopClick = function(e) {
e.preventDefault();
// fire the Chromecast-specific stop function, which will fire the callback defined above
CHROMECAST_SENDER.stopCasting();
}
/*
* Cast receiver mute
*/
var onCastReceiverMute = function(message) {
if (message == 'true') {
$audioPlayer.jPlayer('pause');
} else {
$audioPlayer.jPlayer('play');
}
}
/*
* Unmute the audio.
*/
var onAudioPlayClick = function(e) {
e.preventDefault();
if (is_casting) {
CHROMECAST_SENDER.sendMessage('mute', 'false');
} else {
$audioPlayer.jPlayer('play');
}
$audioPlay.hide();
$audioPause.show();
}
/*
* Mute the audio.
*/
var onAudioPauseClick = function(e) {
e.preventDefault();
if (is_casting) {
CHROMECAST_SENDER.sendMessage('mute', 'true');
} else {
$audioPlayer.jPlayer('pause');
}
$audioPause.hide();
$audioPlay.show();
}
$(document).ready(function() {
$chromecastScreen = $('.cast-controls');
$castStart = $('.cast-start');
$castStop = $('.cast-stop');
$audioPlay = $('.controls .play');
$audioPause = $('.controls .pause');
if (IS_CAST_RECEIVER) {
CHROMECAST_RECEIVER.setup();
// Set up event listeners here
CHROMECAST_RECEIVER.onMessage('mute', onCastReceiverMute);
}
$castStart.on('click', onCastStartClick);
$castStop.on('click', onCastStopClick);
$audioPlay.on('click', onAudioPlayClick);
$audioPause.on('click', onAudioPauseClick);
});
var CHROMECAST_RECEIVER = (function() {
var obj = {};
// define a short delimiter to namespace your messages
var MESSAGE_DELIMITER = 'DEFINE_A_DELIMITER';
var _messageHandlers = {};
var _messageRegex = new RegExp('(\\S+)' + MESSAGE_DELIMITER + '(.+)$');
obj.setup = function() {
var castReceiverManager = cast.receiver.CastReceiverManager.getInstance();
var customMessageBus = castReceiverManager.getCastMessageBus(YOUR_CHROMECAST_NAMESPACE);
customMessageBus.onMessage = onReceiveMessage;
castReceiverManager.start();
}
var onReceiveMessage = function(e) {
var match = e.data.match(_messageRegex);
var messageType = match[1];
var message = match[2];
_fire(messageType, message);
}
var _fire = function(messageType, message) {
if (messageType in _messageHandlers) {
for (var i = 0; i < _messageHandlers[messageType].length; i++) {
_messageHandlers[messageType][i](message);
}
}
};
obj.onMessage = function(messageType, callback) {
if (!(messageType in _messageHandlers)) {
_messageHandlers[messageType] = [];
}
_messageHandlers[messageType].push(callback);
}
return obj;
}());
var CHROMECAST_SENDER = (function() {
var obj = {};
// define a short delimiter to namespace your messages
var MESSAGE_DELIMITER = 'DEFINE_A_DELIMITER';
var _session = null;
var _readyCallback = null;
var _startedCallback = null;
var _stoppedCallback = null;
/*
* Initialize chromecast environment.
*/
obj.setup = function(readyCallback, startedCallback, stoppedCallback) {
_readyCallback = readyCallback;
_startedCallback = startedCallback;
_stoppedCallback = stoppedCallback;
var sessionRequest = new chrome.cast.SessionRequest(YOUR_CHROMECAST_APP_ID);
var apiConfig = new chrome.cast.ApiConfig(
sessionRequest,
sessionListener,
receiverListener,
chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED
);
chrome.cast.initialize(apiConfig, onInitSuccess, onInitError);
}
/*
* Listen for existing sessions with the receiver.
*/
var sessionListener = function(session) {
_session = session;
_session.addUpdateListener(sessionUpdateListener);
if (_startedCallback) {
_startedCallback();
}
}
/*
* Listen for changes to the session status.
*/
var sessionUpdateListener = function(isAlive) {
if (!isAlive) {
if (_stoppedCallback) {
_stoppedCallback();
}
}
}
/*
* Listen for receivers to become available.
*/
var receiverListener = function(e) {
if (e === chrome.cast.ReceiverAvailability.AVAILABLE) {
if (_readyCallback) {
_readyCallback();
}
}
}
/*
* Environment successfully initialized.
*/
var onInitSuccess = function(e) {}
/*
* Error initializing.
*/
var onInitError = function(e) {}
/*
* Start casting.
*/
obj.startCasting = function() {
chrome.cast.requestSession(onRequestSessionSuccess, onRequestSessionError);
}
/*
* Casting session begun successfully.
*/
var onRequestSessionSuccess = function(session) {
_session = session;
_session.addUpdateListener(sessionUpdateListener);
if (_startedCallback) {
_startedCallback();
}
}
/*
* Casting session failed to start.
*/
var onRequestSessionError = function(e) {}
/*
* Stop casting.
*/
obj.stopCasting = function() {
_session.stop(onSessionStopSuccess, onSessionStopError);
}
/*
* Inform client the session has stopped.
*/
var onSessionStopSuccess = function() {
if (_stoppedCallback) {
_stoppedCallback();
}
}
var onSessionStopError = function() {}
/*
* Send a message to the receiver.
*/
obj.sendMessage = function(messageType, message) {
_session.sendMessage(
YOUR_CHROMECAST_NAMESPACE,
messageType + MESSAGE_DELIMITER + message,
onSendSuccess,
onSendError
);
}
/*
* Successfully sent message to receiver.
*/
var onSendSuccess = function(message) {}
/*
* Error sending message to receiver.
*/
var onSendError = function(message) {}
return obj;
}());
The MIT License (MIT)
Copyright (c) 2014 NPR
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment