Facebook login javascript sdk get email
To get the user's email address using the Facebook Login JavaScript SDK, you can use the getLoginStatus
method to check if the user is logged in, and then use the getAuthResponse
method to retrieve the user's authentication response, which includes their email address.
Here is an example of how you can do this:
// Initialize the Facebook SDK
FB.init({
appId: 'YOUR_APP_ID',
cookie: true,
xfbml: true,
version: 'v3.3'
});
// Check if the user is logged in
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// User is logged in, get their authentication response
FB.api('/me', 'GET', { fields: 'email' }, function(response) {
console.log(response.email); // Output: the user's email address
});
} else {
// User is not logged in, prompt them to log in
FB.login(function(response) {
if (response.authResponse) {
// User logged in, get their authentication response
FB.api('/me', 'GET', { fields: 'email' }, function(response) {
console.log(response.email); // Output: the user's email address
});
}
}, { scope: 'email' });
}
});
In this example, we first initialize the Facebook SDK with our app ID and other settings. Then, we use the getLoginStatus
method to check if the user is logged in. If they are, we use the FB.api
method to retrieve their authentication response, which includes their email address. If they are not logged in, we prompt them to log in using the FB.login
method, and then retrieve their authentication response once they have logged in.
Note that the FB.api
method returns a JSON object that contains the user's authentication response, including their email address. You can access the email address by accessing the response.email
property.
Also, make sure to add the email
permission to your Facebook app settings, so that you can access the user's email address.
You can also use the FB.getLoginAuthResponse
method to get the authentication response, it will return an object with the following properties:
{
"authResponse": {
"accessToken": "...',
"expiresIn": 5184000,
"expiresAt": 1643723400,
"permissions": ["email"],
"userID": "..."
}
}
You can access the email address by accessing the authResponse.permissions
property, it will return an array of permissions, and you can check if the email
permission is included in the array.
Please keep in mind that the Facebook Login JavaScript SDK is subject to change, and the above code may not work in the future. It's always a good idea to check the Facebook documentation for the latest information on using the SDK.