diff --git a/site/src/layouts/Base.astro b/site/src/layouts/Base.astro index 2d49be8..e29e2d2 100644 --- a/site/src/layouts/Base.astro +++ b/site/src/layouts/Base.astro @@ -821,25 +821,35 @@ try { const popup = window.open(url, 'strava-auth', 'width=600,height=700,left=200,top=100'); stravaStatus.textContent = 'Waiting for Strava authorisation…'; - // Listen for the callback redirect closing the popup - const poll = setInterval(() => { - try { - if (popup && popup.location.href.includes('strava=connected')) { - clearInterval(poll); - popup.close(); - stravaStatus.textContent = 'Connected!'; - stravaStatus.style.color = '#4ade80'; - stravaConnect.style.display = 'none'; - stravaSync.style.display = ''; - stravaLastSync.textContent = 'never'; - } else if (popup && popup.location.href.includes('strava=error')) { - clearInterval(poll); - popup.close(); - stravaStatus.textContent = 'Authorisation failed.'; + // postMessage listener — works cross-origin (callback may be on a different subdomain) + function onStravaMsg(e: MessageEvent) { + if (!e.data || e.data.stravaAuth === undefined) return; + window.removeEventListener('message', onStravaMsg); + clearInterval(closedPoll); + popup?.close(); + if (e.data.stravaAuth === 'connected') { + stravaStatus.textContent = 'Connected!'; + stravaStatus.style.color = '#4ade80'; + stravaConnect.style.display = 'none'; + stravaSync.style.display = ''; + stravaLastSync.textContent = 'never'; + } else { + stravaStatus.textContent = 'Authorisation failed.'; + stravaStatus.style.color = '#f87171'; + } + } + window.addEventListener('message', onStravaMsg); + + // Fallback: if popup is closed without a message, clean up + const closedPoll = setInterval(() => { + if (popup && popup.closed) { + clearInterval(closedPoll); + window.removeEventListener('message', onStravaMsg); + if (stravaStatus.textContent === 'Waiting for Strava authorisation…') { + stravaStatus.textContent = 'Window closed — authorisation not completed.'; stravaStatus.style.color = '#f87171'; } - } catch (_) {} - if (popup && popup.closed) clearInterval(poll); + } }, 500); } catch (e) { stravaStatus.textContent = 'Error: ' + e.message; @@ -1139,7 +1149,12 @@ try { // Handle ?strava= param set by the callback redirect (popup scenario) const sp = new URLSearchParams(window.location.search); if (sp.has('strava')) { + const stravaVal = sp.get('strava'); history.replaceState(null, '', window.location.pathname); + if (window.opener) { + window.opener.postMessage({ stravaAuth: stravaVal }, '*'); + window.close(); + } } )}