JavaScript API を使用する

必要に応じて、JavaScript コードのみを使用してワンタップ プロンプトをトリガーするか、[Google でログイン] ボタンをレンダリングできます。

JavaScript でワンタップ プロンプトを構成するには、まず initialize() メソッドを呼び出す必要があります。次に、prompt() メソッドを呼び出して、プロンプト UI を表示します。次のコード スニペットをご覧ください。

<script>
  window.onload = function () {
    google.accounts.id.initialize({
      client_id: 'YOUR_GOOGLE_CLIENT_ID',
      callback: handleCredentialResponse
    });
    google.accounts.id.prompt();
  }
</script>

迅速な UI ステータス通知を受け取るには、prompt() メソッドにコールバック関数を提供します。次のコード スニペットをご覧ください。

<script>
  window.onload = function () {
    google.accounts.id.initialize({
      client_id: 'YOUR_GOOGLE_CLIENT_ID',
      callback: handleCredentialResponse
    });
    google.accounts.id.prompt((notification) => {
        if (notification.isNotDisplayed() || notification.isSkippedMoment()) {
            // try next provider if OneTap is not displayed or skipped
        }
    });
  }
</script>

次のコード例は、JavaScript でワンタップと「Google でログイン」ボタンの両方をレンダリングする方法を示しています。

<script>
  window.onload = function () {
    google.accounts.id.initialize({
      client_id: 'YOUR_GOOGLE_CLIENT_ID',
      callback: handleCredentialResponse
    });
    const parent = document.getElementById('google_btn');
    google.accounts.id.renderButton(parent, {theme: "filled_blue"});
    google.accounts.id.prompt();
  }
</script>