编程语言
首页 > 编程语言> > 使用Javascript将动态内容分享到Facebook新闻Feed的最简单方法?

使用Javascript将动态内容分享到Facebook新闻Feed的最简单方法?

作者:互联网

我希望我的用户能够在他们的Facebook新闻源上分享动态内容.没有其他Facebook集成(例如Facebook登录或其他服务器端集成)所以我希望它尽可能轻.

这是我得到的地方,但它看起来如何?它似乎有效,但我不确定我是否已经想到了一切.

<button id="fb-publish">Share to Facebook</button>

<script type="text/javascript">
(function() {
    FB.init({
        appId: MY_FACEBOOK_APP_ID, cookie: true, status: true, xfbml: true, oauth: true
    });
    var fbAuth = null;
    var fbShare = function() {
        FB.ui({
            method: "feed",
            display: "iframe",
            link: "http://example.com/",
            caption: "Example.com",
            description: "Here is the text I want to share.",
            picture: "http://example.com/image.png"
        });
    };
    $("#fb-publish").click(function() {
        if (!fbAuth) {
            FB.login(function(response) {
                if (response.authResponse) {
                    fbAuth = response.authResponse;
                    fbShare();
                }
            }, {scope: 'publish_stream'});
        } else {
            fbShare();
        }
    });
})();
</script>

此外,如果我想从URL附加图像(大于图片字段中定义的50×50像素图像),我怎么能用JavaScript做到这一点?或者我可以吗?

解决方法:

我决定省略authResponse缓存并每次都调用FB.login().它会短暂打开一个弹出窗口,但至少没有用户在另一个选项卡或窗口中注销并且缓存的authResponse已过时的情况.简短闪烁的弹出窗口并不是一个大问题,因为我不认为用户会多次共享同一页面.

这是我的最终代码,它比原始代码更简单:

<button id="fb-publish">Share to Facebook</button>

<script type="text/javascript">
(function() {
    FB.init({
        appId: MY_FACEBOOK_APP_ID, cookie: true, status: true, xfbml: true, oauth: true
    });
    var fbShare = function() {
        FB.ui({
            method: "feed",
            display: "iframe",
            link: "http://example.com/",
            caption: "Example.com",
            description: "Here is the text I want to share.",
            picture: "http://example.com/image.png"
        });
    };
    $("#fb-publish").click(function() {
        FB.login(function(response) {
            if (response.authResponse) {
                fbShare();
           }
        }, {scope: 'publish_stream'});
    });
})();
</script>

正如Tolga Arican所提到的,如果你可以在弹出窗口中打开共享对话框,你甚至不需要调用FB.login()并要求获得publish_stream权限;直接调用FB.ui({method:“feed”}),你就可以了:

<button id="fb-publish">Share to Facebook</button>

<script type="text/javascript">
(function() {
    FB.init({
        appId: MY_FACEBOOK_APP_ID, cookie: true, status: true, xfbml: true, oauth: true
    });
    $("#fb-publish").click(function() {
        FB.ui({
            method: "feed",
            link: "http://example.com/",
            caption: "Example.com",
            description: "Here is the text I want to share.",
            picture: "http://example.com/image.png"
        });
    });
})();
</script>

标签:javascript,facebook,facebook-graph-api,share,facebook-like
来源: https://codeday.me/bug/20190709/1417519.html