Giter Club home page Giter Club logo

cordova-chromecast's Introduction

DISCLAIMER

This repo is no longer maintained. If you want to contribute, feel free to submit PR's.

Chromecast plugin for Cordova

I have forked this repo out of Exozet's repo, because I wanted to bugfix or rather fix plugin's communication with the Chromecast. You can find a working demo at the bottom of this readme.

Original repo

https://github.com/GetVideostream/cordova-chromecast.git

Exozet's repo

Exozet created fixes required for the plugin to run on the latest cordova versions

https://github.com/exozet/cordova-chromecast.git

Installation

For now, add the plugin from this repository.

cordova plugin add https://github.com/nbabanov/cordova-chromecast.git

If you have NodeJS installed, the dependencies should be automatically copied.

  • http://nodejs.org/

If not you will need to import the following projects as Library Projects in order for this plugin to work:

  • adt-bundle\sdk\extras\google\google_play_services\libproject\google-play-services_lib
  • adt-bundle\sdk\extras\android\support\v7\appcompat
  • adt-bundle\sdk\extras\android\support\v7\mediarouter

Usage

This project attempts to implement the official Google Cast SDK for Chrome... in Cordova. We've made a lot of progress in making this possible, check out the offical docs for examples: https://developers.google.com/cast/docs/chrome_sender

When you call chrome.cast.requestSession() an ugly popup will be displayed to select a Chromecast. If you're not cool with this - you can call: chrome.cast.getRouteListElement() which will return a <ul> tag that contains the Chromecasts in a list. All you have to do is style that bad boy and you're off to the races!

Demo

if (!chrome.cast || !chrome.cast.isAvailable) {
    setTimeout(initializeCastApi, 1000);
}

var initializeCastApi = function () {
    var sessionRequest = new chrome.cast.SessionRequest(chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID);
    var apiConfig = new chrome.cast.ApiConfig(sessionRequest,
        sessionListener,
        receiverListener);
    chrome.cast.initialize(apiConfig, onInitSuccess, onError);
};


function receiverListener(e) {
    if (e === chrome.cast.ReceiverAvailability.AVAILABLE) {
        console.log(e);
    }
}
var castSession = null;
var currentMedia = null;

/**
*	Calling the castConnect function, a popup will show to choose from available devices
*/
function castConnect() {
    castSession = null;
    chrome.cast.requestSession(onRequestSessionSuccess, onLaunchError);
}

/**
*	|	Event listeners
*	V
*/

function onRequestSessionSuccess(e) {
    castSession = e;
}

function onLaunchError(e) {
    console.error(e);
}

function sessionListener(e) {
    console.log('sessionListener');
    console.log(e);
}

function receiverListener(e) {
    console.log('receiverListener');
    console.log(e);
}

function onInitSuccess(e) {
    console.log('onInitSuccess');
    console.log(e);
}

function onError(e) {
    console.error('onError');
    console.error(e);
}

function onMediaDiscovered(how, media) {
    console.log(how);
    currentMedia = media;
}

function onMediaError(e) {
    console.error('onMediaError');
    console.error(e);
}


/**
*	Sends media to the chromecast
*	NOTE: Default receiver only accepts media files (videos, audio and/or subtitles)	
*
*	@param {string} url - url
*	@param {string} type - mime type 
*/

function sendMedia(url, type) {
    var mediaInfo = new chrome.cast.media.MediaInfo(url, type);

    var request = new chrome.cast.media.LoadRequest(mediaInfo);
    castSession.loadMedia(request,
        onMediaDiscovered.bind(this, 'loadMedia'),
        onMediaError);
}

cordova-chromecast's People

Contributors

klaasvanderlinden avatar nbabanov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

cordova-chromecast's Issues

plugin not being recognized by app - Uncaught ReferenceError: chrome is not defined

Uncaught ReferenceError: chrome is not defined
at CastPlayer.initializeCastPlayer (CastVideos.js:138)
at new CastPlayer (CastVideos.js:118)
at index.js:57
at HTMLScriptElement.script.onload (index.js:74)

I keep getting this error while trying to use this plugin on Apache Cordova android 6.3.0 with the target SDK version being 26 and node.js 8.8.1 installed.

I tried just creating a basic app with the code from the demo section but got the same error. I also tried using the code from this project: https://github.com/Vaporexpress/Cordova-CastVideos-chrome.

Initialization problem

Hi Nikolay,

Thanks for this plugin, it is just what I need for radio app I am working on. But up to now I don't get it working. The build process doen't give any errors, but using your example code I can't get it initialized. When I call initializeCastApi() I get the error: 'Cannot read property 'SessionRequest' of undefined'. So it seems that the object chrome.cast is not defined. It's probably a simple mistake I make, but I can't figure it out.

Thanks,
Frans Schrijver

errorCallback is not a function

Hello,

I have just installed this plugin and when i am using this i am getting error:

Please guide me on how can i solve this and get the list of chrome cast devices.

Uncaught TypeError: errorCallback is not a function
    at Object.chrome.cast.requestSession (chrome.cast.js:518)
    at Channel.onDeviceReady (index.html:47)
    at Channel.fire (cordova.js:846)
    at cordova.js:231

and my index.html file is:

<!DOCTYPE html>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->
<html>
    <head>
        <!--
        Customize this policy to fit your own app's needs. For more guidance, see:
            https://github.com/apache/cordova-plugin-whitelist/blob/master/README.md#content-security-policy
        Some notes:
            * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
            * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
            * Disables use of inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
                * Enable inline JS: add 'unsafe-inline' to default-src
        -->
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <title>Hello World</title>
        <script type="text/javascript" charset="utf-8">
    
        // Wait for device API libraries to load
        //
        function onLoad() {
            document.addEventListener("deviceready", onDeviceReady, false);
        }
    
        // device APIs are available
        //
        function onDeviceReady() {
            chrome.cast.requestSession();
        }
    
        </script>
    </head>
    <body onload="onLoad()">
        <div class="app">
            <h1>Apache Cordova</h1>
            <div id="deviceready" class="blink">
                <p class="event listening">Connecting to Device</p>
                <p class="event received">Device is Ready</p>
            </div>
        </div>
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
    </body>
</html>

Unable to install plugin

Hi,
I'm trying to install this plugin in my existing cordova project. My project currently doesn't have play service support. I'm using cordova 7.0.1 on my windows system.
below are the error logs which I get just after running the add plugin command. i.e.
cordova plugin add https://github.com/nbabanov/cordova-chromecast.git

Error: Failed to fetch plugin https://github.com/nbabanov/cordova-chromecast.git via registry.
Probably this is either a connection problem, or plugin spec is incorrect.
Check your connection and plugin name/version/URL.
Error: cmd: Command failed with exit code 4294963228 Error output:
npm ERR! addLocal Could not install C:\Users\shash\AppData\Local\Temp\npm-5956-21293606\git-cache-5bcb71aa\81ebbf80ea2513395ef8d695c0d
b612bd2e36e1a
npm ERR! Windows_NT 10.0.15063
npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Users\shash\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js" "ins
tall" "https://github.com/nbabanov/cordova-chromecast.git" "--save"
npm ERR! node v6.11.0
npm ERR! npm v3.10.10
npm ERR! code EISDIR
npm ERR! errno -4068
npm ERR! syscall read

npm ERR! eisdir EISDIR: illegal operation on a directory, read
npm ERR! eisdir This is most likely not a problem with npm itself
npm ERR! eisdir and is related to npm not being able to find a package.json in
npm ERR! eisdir a package you are trying to install.

npm ERR! Please include the following file with any support request:
npm ERR! D:\Shashank\Cordova\Gazebo\Gazebo-New\node_modules\npm-debug.log

onLaunchError

Hello @nbabanov

Why i am getting onLaunchError? Testing on emulator.

chrome.cast.Error
code: "receiver_unavailable"
description: "No receiver was compatible with the session request."
function onRequestSessionSuccess(){
 alert(1);
}

function onLaunchError(e) {
 console.error(e);
}

function onDeviceReady() {
 chrome.cast.requestSession(onRequestSessionSuccess, onLaunchError);
}

help with initialization

Hi,
Im trying to connect chromecast to my android ionic hybrid app.

on a browser that code works ... :

<script type="text/javascript"> window['__onGCastApiAvailable'] = function(isAvailable) { if (isAvailable) { var options = {}; options.receiverApplicationId = '06CCA653'; options.autoJoinPolicy = chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED; cast.framework.CastContext.getInstance().setOptions(options); } }; </script>

My first problem was that isAvailable was always false, but after installing your plugin, it became true.
So, your plugin is well installed.

The question is if can I do something like that code, because that : " cast.framework.CastContext.getInstance().setOptions(options); " gives me an error Uncaught ReferenceError: cast is not defined

I am using that cordova plugin on Ionic.

With your example code, My chromecast is not beeing connected, the console:

initialize tab_and_origin_scoped 06CCA653
index.html:124 onInitSuccess
index.html:125 undefined
index.html:119 receiverListener
index.html:120 unavailable

Thanks.

Trigger Media Play/Pause or Seek

I have a couple questions

  1. How would I go about triggering "mediaPlay" , "mediaPause" or "mediaSeek" ?
  2. How do I load cast starting at a specific time

1.)
I tried adding the snippet below to chrome.cast.js :

chrome.cast.Session.prototype.pause = function (successCallback, errorCallback) {
        if (chrome.cast.isAvailable === false) {
            errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {});
            return;
        }

        execute('mediaPlay', function (err) {
            if (!err) {
                successCallback && successCallback();
            } else {
                handleError(err, errorCallback);
            }
        });
    };

and call is via :

 castSession.pause(
                function successCallback(){
                    log('Pause Cast content');
                }, 
                function errorCallback(){
                    log('Failed to pause content');
                });

This does not seem to work, any ideas ?

2.)

I tried modifying LoadRequest to take a _currentTime parameter

LoadRequest: function (media, _currentTime) {
               this.type = 'LOAD';
               this.sessionId = this.requestId = this.customData = null;
               this.media = media;
               this.autoplay = !0;

               if(_currentTime){
                   this.currentTime  = _currentTime;
               }
           }

Cast only working on DEFAULT_MEDIA_RECEIVER_APP_ID

Hi!
Great plugin! I added it to my device and everything seems to work fine with default media reiceiver.

Then I created my own Styled Media Receiver in the Google Cast SDK Developer Console. Added the id to the chrome.cast.SessionRequest and booted the app. When clicking connect and selecting my Chromecast device from the default popup list, the app crashes every time.

What am I missing here? I've added my device to the Google Cast SDK DC and published the application there.

INIT

  var sessionRequest = new chrome.cast.SessionRequest("VALID_ID");
  var apiConfig = new chrome.cast.ApiConfig(
    sessionRequest,
    function(e) /* sessionListener */
    {
      /* Do nothing */
    },
    function(e) /* receiverListener */
    {
      if (e === chrome.cast.ReceiverAvailability.AVAILABLE)
      {
        AppMusic.Chromecast.receiverAvailable = true;
        AppMusic.Chromecast.setBtnDisabled(false);
      }
      else
      {
        AppMusic.Chromecast.receiverAvailable = false;
        AppMusic.Chromecast.setBtnInactive();
        AppMusic.Chromecast.setBtnDisabled(true);
      }
    }
  );

  chrome.cast.initialize(
    apiConfig,
    function() /* onInitSuccess */
    {
      AppMusic.Chromecast.ready = true;
    },
    function(e) /* onError */
    {
      AppMusic.Chromecast.showError(AppMusic.Lang.get("error_chromecast_initialize"), e);
    }
  );

CONNECT

chrome.cast.requestSession(
  function(e)
  {
    /* onRequestSessionSuccess */
    AppMusic.Chromecast.castSession = e;
    AppMusic.Chromecast.setBtnActive();
  },
  function(e)
  {
    /* onLaunchError */
    AppMusic.Chromecast.showError(AppMusic.Lang.get("error_chromecast_connect"), e);
  }
);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.