2014-12-14

Client-side Facebook Access Token Retrieval

Save this HTML5 app as facebook-accessToken.html:
<!DOCTYPE html>

<div id="fb-root"></div>
<div class="facebook">Log in with Facebook</div>
<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script>
    $(document).ready(function () {
        (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/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
        }

        (document, 'script', 'facebook-jssdk'));
        window.fbAsyncInit = function () {
            FB.init(
                    {
                        appId: 'App ID, e.g. 2496324382648314, ' +
                        'can be retrieved from ' +
                        'https://developers.facebook.com, under Apps',
                        cookie: false,
                        xfbml: true,
                        version: 'v2.1'                    }
            );

            $('.facebook').on('click', function () {
                FB.login(function (response) {
                    console.log(response.authResponse.accessToken);
                    console.log(response);
                    if (response.authResponse) {
                        FB.api('/me', function (response) {
                                    console.log(response.name);
                                }
                        );
                    }
                });
            })

        };
    });
</script>

Start a web server on port 80 in the directory where you saved this HTML5 app, executing:
sudo python -m SimpleHTTPServer 80
The web browser console should print something like this:
[Log] CAAUsh234342IUSSDASDsGZAicW7WqmcJreEOzenjJ5kBvuMSDKLJASD224QNHcQ5vM1LPlQBjqWONoSc4zKlUtnnjGfVLNwDuLjZBASD24234CgZAYjiPqTl2p6xVM0hWTh86utuJ99PLXywHg9ZCrMjU6d52DQTnOfXgq0OdzxS (facebook-accessToken.html, line 30) 
[Log] Object (facebook-accessToken.html, line 31) 
[Log] Alexander Orlov (facebook-accessToken.html, line 34)
when you access it using e.g. Cmd + Opt + I in Safari.