Fix Strava OAuth popup detection via postMessage (cross-origin safe)
This commit is contained in:
+26
-11
@@ -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();
|
||||
// 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 if (popup && popup.location.href.includes('strava=error')) {
|
||||
clearInterval(poll);
|
||||
popup.close();
|
||||
} else {
|
||||
stravaStatus.textContent = 'Authorisation failed.';
|
||||
stravaStatus.style.color = '#f87171';
|
||||
}
|
||||
} catch (_) {}
|
||||
if (popup && popup.closed) clearInterval(poll);
|
||||
}
|
||||
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';
|
||||
}
|
||||
}
|
||||
}, 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();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user