Self-Development: Productivity & Time Management
Self Development |
2025-02-25 08:44:05
To implement Facebook auto-login on your website, you need to use Facebook Login with the JavaScript SDK. This allows users to log in automatically if they are already logged into Facebook.
Add the following script inside the <body>
tag of your HTML file:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // Replace with your Facebook App ID
cookie : true,
xfbml : true,
version : 'v18.0' // Use the latest Facebook Graph API version
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function statusChangeCallback(response) {
if (response.status === 'connected') {
// User is logged in and has authenticated your app
fetchUserInfo();
} else {
// Not logged in, show login button
document.getElementById('fb-login-btn').style.display = 'block';
}
}
function fetchUserInfo() {
FB.api('/me', {fields: 'id, name, email'}, function(response) {
console.log('User Info:', response);
document.getElementById('user-info').innerHTML =
'Welcome, ' + response.name + '! (' + response.email + ')';
});
}
function loginWithFacebook() {
FB.login(function(response) {
if (response.authResponse) {
fetchUserInfo();
}
}, {scope: 'email'});
}
</script>
<button id="fb-login-btn" onclick="loginWithFacebook()" style="display:none;">
Login with Facebook
</button>
<div id="user-info"></div>
FB.getLoginStatus()
checks if the user is already logged into Facebook.Would you like a backend implementation with token validation as well?