Facebook javascript sdk get email
To get the email of a Facebook user using the Facebook JavaScript SDK, you can use the FB.api
method to make a request to the Facebook Graph API. Here's an example:
FB.api('/me', 'GET', { fields: 'email' }, function(response) {
if (response &&!response.error) {
console.log(response.email);
} else {
console.log('Error: ' + response.error.message);
}
});
In this example, we're making a GET request to the /me
endpoint, which returns information about the currently logged-in user. We're specifying the fields
parameter to request only the email
field.
When the response is received, we're checking if the response is successful (i.e., response.error
is null
) and if so, we're logging the user's email address to the console.
Note that the FB.api
method is only available after the user has authenticated with your app and granted the necessary permissions. You'll need to include the email
permission in your app's authorization settings and request it when the user logs in.
Here's an example of how you can request the email
permission when the user logs in:
FB.login(function(response) {
if (response.authResponse) {
// User has granted permissions
FB.api('/me', 'GET', { fields: 'email' }, function(response) {
//...
});
} else {
// User has declined permissions
}
}, { scope: 'email' });
In this example, we're using the FB.login
method to request the email
permission when the user logs in. The scope
parameter specifies the permissions we're requesting.