每次打开或重新加载页面时,浏览器都会要求进行Google登录,怎么解决?

前端开发 2026-07-11

这是我的代码,使用了Google Sign-in,完全来自Google日历API文档。

它可以运行。 然而,每次打开页面或重新加载时,它都会调用Google Sign-in。

我想不出怎样让认证保持持久。

有什么想法?

<script type="text/javascript">
    // Credentials to authenticate with Google API 
    const CLIENT_ID = 'XXX';
    const API_KEY = 'YYY';
    const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest';
    const SCOPES = 'https://www.googleapis.com/auth/calendar.readonly';

    let tokenClient;
    let gapiInited = false;
    let gisInited = false;

    function gapiLoaded() {
      gapi.load('client', initializeGapiClient);
    }

    async function initializeGapiClient() {
      await gapi.client.init({
        apiKey: API_KEY,
        discoveryDocs: [DISCOVERY_DOC],
      });
      gapiInited = true;
      maybeAuthorize();
    }

    function gisLoaded() {
      tokenClient = google.accounts.oauth2.initTokenClient({
        client_id: CLIENT_ID,
        scope: SCOPES,
        callback: async (resp) => {
          if (resp.error) {
            console.error(resp);
            document.getElementById('content').innerText = 'Authorization failed.';
            console.error('Error during authorization:', resp);
            return;
          }
          await createAllContent();
        },
      });
      gisInited = true;
      maybeAuthorize();
    }

    function maybeAuthorize() {
      if (gapiInited && gisInited) {
        authorize();
      }
    }

    function authorize() {
      if (gapi.client.getToken() === null) {
        // First try silent auth (no UI)
        tokenClient.requestAccessToken({ prompt: '' });
      } else {
        // Already signed in
        createAllContent();
      }
    }

    // Create all content
    function createAllContent() {
      // Some functionality that uses Google API (gapi)
    }

  </script>
  <script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
  <script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>

解决方案

gapi.client.getToken() 是在内存中的,因此在重新加载时会丢失。

Fix: 将令牌持久化并恢复。

// restore
const t = JSON.parse(localStorage.getItem('gapi_token'));
if (t) {
  gapi.client.setToken(t);
  createAllContent();
} else {
  tokenClient.requestAccessToken({ prompt: '' });
}

// save
callback: (resp) => {
  gapi.client.setToken(resp);
  localStorage.setItem('gapi_token', JSON.stringify(resp));
  createAllContent();
}

因此,请重试使用 prompt: '',若失败则回退到 'consent'

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章