From b02f5aa78020270c2fd0f74338e297b92a001521 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaroslav=20Polakovi=C4=8D?= Date: Mon, 31 Jan 2022 13:27:27 +0100 Subject: [PATCH] Only return the casting button when there are devices to cast to. --- src/index.js | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/src/index.js b/src/index.js index 1250067..e1a04ab 100644 --- a/src/index.js +++ b/src/index.js @@ -170,20 +170,40 @@ window.kinoInitGoogleCast = (function kinoInitGoogleCastIIFE() { return () => { if (!castButtonPromise) { castButtonPromise = new Promise((resolve) => { - const initCastApi = () => { - window.cast.framework.CastContext.getInstance().setOptions({ - receiverApplicationId: window.chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID, - }); + let resolved = false; + const resolveWithButton = () => { const castButton = document.createElement('button'); const castCustomElement = document.createElement('google-cast-launcher'); castButton.setAttribute('aria-label', 'Cast this video'); castButton.appendChild(castCustomElement); + resolved = true; resolve(castButton); }; + const checkCastState = () => { + const castState = window.cast.framework.CastContext.getInstance().getCastState(); + + if (castState !== 'NO_DEVICES_AVAILABLE' && !resolved) { + resolveWithButton(); + } + }; + + const initCastApi = () => { + window.cast.framework.CastContext.getInstance().setOptions({ + receiverApplicationId: window.chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID, + }); + + checkCastState(); + + window.cast.framework.CastContext.getInstance().addEventListener( + window.cast.framework.CastContextEventType.CAST_STATE_CHANGED, + checkCastState, + ); + }; + window.__onGCastApiAvailable = (isAvailable) => { if (isAvailable) { initCastApi();