You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

新手求教:如何用JavaScript获取并展示当前登录用户的邮箱ID?

获取登录用户邮箱并展示(类似谷歌首页功能)

Hey there! Let's break this down clearly since you're new to programming—building a Google Home page-like project is a fantastic way to pick up core web development skills.

First, a critical heads-up: you can't directly grab a user's email from a plain frontend webpage—browsers have strict security rules to protect user privacy. To access this info, you need to use an authentication system where the user explicitly grants permission, just like Google does with its sign-in flow. We'll use Google's official OAuth 2.0 tooling for this, which is the standard approach.

Step 1: Set Up Your Google Developer Account & OAuth Client ID

Before writing code, you need to create a project in Google Cloud Console to get a client ID (this lets Google recognize your app):

  • Go to Google Cloud Console, create a new project.
  • Navigate to APIs & Services > OAuth consent screen, choose "External" (for testing) and fill in basic info (like app name, support email).
  • Go to APIs & Services > Credentials, click "Create Credentials > OAuth client ID".
  • Select "Web application" as the application type. Add your local development URL (e.g., http://localhost:8000) under "Authorized JavaScript origins" and "Authorized redirect URIs".
  • Copy the generated client ID—you'll need this in your code.

Step 2: Write the HTML Structure

Create a simple HTML page with a sign-in button and a spot to display the email:

<!DOCTYPE html>
<html>
<head>
    <title>Google-like Home Page</title>
    <style>
        /* Add some basic styling to mirror Google's clean look */
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-top: 100px;
            font-family: Arial, sans-serif;
        }
        #loginBtn {
            padding: 10px 20px;
            background-color: #4285F4;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        #emailDisplay {
            margin-top: 20px;
            font-size: 18px;
        }
    </style>
</head>
<body>
    <button id="loginBtn">Sign in with Google</button>
    <div id="emailDisplay"></div>

    <!-- Load Google's OAuth client library -->
    <script src="https://accounts.google.com/gsi/client" async defer></script>
    <script src="app.js"></script>
</body>
</html>

Step 3: Add JavaScript Logic (app.js)

This code handles the sign-in flow, retrieves the user's email, and displays it:

// Initialize Google's authentication client when the page loads
window.onload = function() {
    // Replace this with your actual client ID from Google Cloud Console
    const YOUR_CLIENT_ID = 'your-client-id-here';
    
    google.accounts.id.initialize({
        client_id: YOUR_CLIENT_ID,
        callback: handleLoginSuccess // Function to run after successful sign-in
    });

    // Attach click event to the sign-in button
    document.getElementById('loginBtn').addEventListener('click', () => {
        google.accounts.id.prompt(); // Show the Google sign-in popup
    });
};

// Handle the response after user signs in
function handleLoginSuccess(response) {
    // Decode the ID token to get user data (it's a base64-encoded JSON string)
    const userPayload = JSON.parse(atob(response.credential.split('.')[1]));
    const userEmail = userPayload.email;

    // Display the email on the page
    document.getElementById('emailDisplay').textContent = `Signed in as: ${userEmail}`;
}

Step 4: Test Your Code

  • You can't just open the HTML file directly (browsers block local files from accessing external APIs). Instead, run a local web server:
    • If you have Python installed, run python -m http.server 8000 in your project folder.
    • Open your browser and go to http://localhost:8000.
  • Click the "Sign in with Google" button, select your Google account, and grant permission. You'll see your email displayed!

Important Notes

  • Never share your client ID publicly (like in a public GitHub repo)—it's tied to your project and could be misused.
  • If you want to build a custom login system (not using Google), you'll need a backend server: after the user logs in with a username/password, your backend can send the email to the frontend to display.
  • For production use, you'll need to update the OAuth consent screen to "Internal" (if it's for your organization) or complete the verification process for external apps.

内容的提问来源于stack exchange,提问作者Code NCraft

火山引擎 最新活动