Quick and Dirty Facebook JS oAuth example

You, FacebookoAuth
Back

This is a really simple FB oAuth code that I used in a project I recently worked. This does a really simple job but this will might help someone to start something big. This will basically authenticate user and import user data like email in to a text box.

Add these in to body with <script> tags.

window.fbAsyncInit = function () {
    // init the FB JS SDK
    FB.init({
        appId: 'YOUR APP ID',
        // App ID from the app dashboard
        channelUrl: '//mysite.local/',
        // Channel file for x-domain comms
        status: true,
        // Check Facebook Login status
        xfbml: true // Look for social plugins on the page
    });
    // Additional initialization code such as adding Event Listeners goes here
};

// Load the SDK asynchronously
(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 = "//connect.facebook.net/en\_US/all.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

This will include the JS library and make FB object available for use.

Next, create a div. 

<p><div class="user-info"></div><a class="import-facebook" href="#">Import E-mail from Facebook</a></p>

Now add below JS to make that link work.

$('.import-facebook').click(function () {
    FB.login(function (response) {
        if (response.authResponse) {
            console.log('Welcome!  Fetching your information.... ');
            FB.api('/me', function (response) {
                console.log('Good to see you, ' + response.name + '.');
                console.log(response);
                var profile\_pic = '<img src="https://graph.facebook.com/' + response.id + '/picture">' + response.name;
                $('.user-info').html(profile\_pic);
                $('.import-facebook').hide();
            });
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    }, {
        scope: 'email'
    });
    return false;
});
© Heshan Wanigasooriya.RSS

🍪 This site does not track you.