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

Vis*_*opu 5 javascript share facebook facebook-like facebook-graph-api

我希望我的用户能够在他们的 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>
Run Code Online (Sandbox Code Playgroud)

另外,如果我想附加来自 URL 的图像(大于字段中定义的 50x50 像素图像picture),我如何仅使用 JavaScript 来做到这一点?或者我可以吗?

Vis*_*opu 1

我决定放弃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>
Run Code Online (Sandbox Code Playgroud)

正如 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>
Run Code Online (Sandbox Code Playgroud)