LoginSignup
2
0

More than 3 years have passed since last update.

facebookへのシェア(投稿)完了を取得する(share dialog)

Last updated at Posted at 2020-01-27

はじめに

「ユーザーがfacebookにシェア(投稿)したら、ボーナスポイントを貰える」要件を実現するために、
調査したことの忘備録です。
webアプリにfacebookシェアを組み込んだものになります。
公式ドキュメント

本当にシェアされたのか気にしないのであれば、以下のようにシェアURLを作成するのみで良いのかなと思います。
https://qiita.com/takuhito-h/items/891f3d53ad14a1182963
https://qiita.com/Ancient_Scapes/items/d27a3e2b247fa43e39f9#_reference-9a76d2b1df20cb6678ae

この記事を執筆した時点での情報になります。
facebook API version: v5.0

結論

投稿完了のcallbackは取得できるが、post_id(投稿されたID)は取得することができない


<body>
<div>
  <button class="post-facebook-btn">facebookへ投稿 share dialogで</button>
</div>
<script>
window.fbAsyncInit = function() {
    FB.init({
    appId      : '{your_app_id}',
    cookie: true,
    xfbml      : true,
    version    : 'v5.0'
    });
    FB.AppEvents.logPageView();
};

(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 = "https://connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
</script>
</body>
<script>
document.getElementsByClassName('post-facebook-btn')[0].onclick = function () {
     // hashtagは['#project', '#hoge'] みたく複数渡せるかと思いきや、最初のものしか渡せない https://stackoverflow.com/questions/37162843/how-can-i-use-multi-hashtags-on-facebook
    // https://developers.facebook.com/docs/sharing/reference/share-dialog
    // 公式にも型の記述がなくよくわからなかった
    FB.ui({
        display: 'popup',
        method: 'share',
        href: 'https://developers.facebook.com/docs/',
        redirect_uri: '{your_redirect_uri}',
        hashtag: '#hashtag'
    }, function(response) {
        // 投稿完了すると response = []が引数に渡される
        // 空配列はtrueを判定されることを利用する
        if (response && !response.error_message) {
            console.log(response) // -> []
            alert('Posting completed.');
        } else {
            console.log(response) // -> undefined
            // FB投稿せずにキャンセル(ページを閉じても)するとresponseがundefinedとなる
            alert('Error while posting.');
        }
    });
}

終わりに

facebookはテストユーザーを用意してくれてるので、気兼ねなく投稿のデバッグができて助かった。
https://developers.facebook.com/docs/apps/test-users?locale=ja_JP
誰かの助けになれば幸いです。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0