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>