简体   繁体   中英

Facebook SDK not working with Javascript

I'm trying to simply make a post to facebook using Javascript/Typescript.

Nothing is working however.

This is my typescript code:

(window as any). //couldn't get code to compile without this...

window.fbAsyncInit = function() {
    FB.init({
        appId: 'MY API KEY',
        xfbml: true,
        version: 'v2.7'
    });
};

(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'));

declare var FB:any;
// Only works after `FB.init` is called
function myFacebookLogin() {
    FB.login(function(){
        // Note: The call will only work if you accept the permission request
        FB.api('/me/feed', 'post', {message: 'Hello, world!'});
    }, {scope: 'publish_actions'});
}

And my HTML:

<script src="./js/main.js"></script>     

<div id="fb-root"></div>

<button onclick="myFacebookLogin()">Login with Facebook</button>    
<div id="status">
</div>    
</body>
</div>
</html>

I got the above code from the facebook developer site.

First, you don't need to cast window to any , you can do this:

interface Window {
    fbAsyncInit: () => void;
}

Then this should work:

window.fbAsyncInit = function() {
    FB.init({
        appId: 'MY API KEY',
        xfbml: true,
        version: 'v2.7'
    });
};

As for the login, according to the docs you are missing the part which handles the error. The function that you pass to FB.login receives a response with which you can check the status:

function myFacebookLogin() {
    FB.login(function(response) {
        if (response.authResponse) {
            FB.api('/me/feed', 'post', { 
                message: 'Hello, world!'
            });
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    }, {scope: 'publish_actions'});
}

Now you'll know if the login failed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM