You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS实现Strava授权弹窗跳转后关闭及获取code参数方案

Strava OAuth授权弹窗处理方案

1. 授权完成后自动关闭弹窗

用户授权成功后会跳转到你设置的redirect_uri页面(也就是http://localhost/exchange_token),在这个页面里加一段JS代码,就能自动关闭弹窗,同时把授权码传给主页面:

<!-- exchange_token 页面的核心代码 -->
<script>
// 从URL里提取code参数
const params = new URLSearchParams(window.location.search);
const authCode = params.get('code');

// 如果主窗口存在,把code传过去
if (window.opener && authCode) {
  window.opener.postMessage({
    type: 'STRAVA_AUTH_SUCCESS',
    code: authCode
  }, window.opener.origin);
}

// 直接关闭当前弹窗
window.close();
</script>

2. 主页面接收code并进行后续调用

修改你原来的弹窗代码,添加消息监听,接收弹窗传过来的code,之后就可以用这个code去换Strava的访问令牌:

// 主页面打开授权弹窗的代码
function openStravaAuth() {
  const authUrl = 'https://www.strava.com/oauth/authorize?client_id=123456&response_type=code&redirect_uri=http://localhost/exchange_token&approval_prompt=force&scope=activity:read_all';
  // 设置弹窗尺寸,降低被浏览器拦截的概率
  const authPopup = window.open(authUrl, 'Strava授权', 'width=600,height=700,top=100,left=100,popup=true');

  // 监听来自弹窗的消息
  function handleAuthMessage(event) {
    // 验证消息来源,防止恶意请求(必须和主页面域名一致)
    if (event.origin !== window.location.origin) return;

    if (event.data.type === 'STRAVA_AUTH_SUCCESS' && event.data.code) {
      const code = event.data.code;
      console.log('拿到授权码:', code);
      
      // 调用自己的后端接口换令牌(绝对不能把client_secret放前端!)
      exchangeCodeForToken(code);
      
      // 用完就移除监听,避免重复触发
      window.removeEventListener('message', handleAuthMessage);
    }
  }

  window.addEventListener('message', handleAuthMessage);
}

// 示例:用授权码换访问令牌(实际要放后端)
async function exchangeCodeForToken(code) {
  try {
    // 这里应该调用你自己的后端接口,由后端去请求Strava的token接口
    const res = await fetch('/your-backend-api/strava-exchange-token', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ code })
    });

    const tokenData = await res.json();
    if (tokenData.access_token) {
      // 保存令牌,后续调用Strava API就用这个
      localStorage.setItem('strava_token', tokenData.access_token);
      console.log('令牌获取成功');
    }
  } catch (err) {
    console.error('换令牌失败:', err);
  }
}

重要提醒

  • 绝对不要把client_secret写在前端代码里:Strava的令牌交换需要client_secret,这个密钥必须存在你的后端服务器,前端只能通过自己的后端接口去完成交换,不然密钥泄露会导致你的应用被滥用。
  • 弹窗配置:给弹窗指定明确的尺寸和位置,比单纯写popup=true更不容易被浏览器的弹窗拦截机制挡住。
  • 消息验证:一定要检查event.origin,只处理来自你自己域名的消息,防止跨域恶意攻击。

内容的提问来源于stack exchange,提问作者Jan D.M.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 08:30:24