简体   繁体   English

Facebook SDK无法使用Javascript

[英]Facebook SDK not working with Javascript

I'm trying to simply make a post to facebook using Javascript/Typescript. 我正在尝试使用Javascript / Typescript在Facebook上发布帖子。

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: 而我的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. 我从Facebook开发者网站获得了以上代码。

First, you don't need to cast window to any , you can do this: 首先,您不需要将window投射到any ,您可以这样做:

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: 传递给FB.login的函数会收到response ,您可以使用该response检查状态:

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. 现在,您将知道登录是否失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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