代码
"use client";
import React, { useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
const GoogleSignInButton: React.FC = () => {
const searchParams = useSearchParams();
const login = searchParams.get('login'); // 获取 URL 参数
useEffect(() => {
// 动态加载 Google 登录脚本
const script = document.createElement('script');
script.src = 'https://accounts.google.com/gsi/client';
script.async = true;
script.defer = true;
document.body.appendChild(script);
// 初始化 Google 登录
script.onload = () => {
if (window.google) {
window.google.accounts.id.initialize({
client_id: process.env.GOOGLE_CLIENT_ID, // 你的 Google Client ID
callback: handleCredentialResponse, // 登录回调函数
ux_mode: 'popup', // 使用弹出窗口模式
});
// 如果 URL 中有 login=true 参数,自动触发登录
if (login === 'true') {
window.google.accounts.id.prompt();
}
}
};
return () => {
// 组件卸载时移除脚本
document.body.removeChild(script);
};
}, [login]);
// 处理 Google 登录回调
const handleCredentialResponse = (response: any) => {
console.log('Google login response:', response);
// 在这里处理登录逻辑,例如发送 credential 到后端验证
};
return (
<>
{/* Google 登录容器 */}
<div
id="g_id_onload"
data-client_id={process.env.GOOGLE_CLIENT_ID}
data-context="signin"
data-ux_mode="popup"
data-login_uri="http://localhost:3000/auth"
data-auto_prompt="false"
></div>
{/* Google 登录按钮 */}
<div
className="g_id_signin"
data-type="standard"
data-shape="rectangular"
data-theme="outline"
data-text="signin_with"
data-size="large"
data-logo_alignment="left"
></div>
</>
);
};
export default GoogleSignInButton;
显示效果
点击这个按钮之后就会直接唤起谷歌登录窗口了