Using Facebook Comment Plugin in Angular/Ionic 2+

Ionic2 Facebook Angular 2

In order to use Facebook's comment plugin in a single-page app, we must modify the provided script. Otherwise, you'll find that the comments fail to show up on the second page. This is because the script is loaded only once at startup, and it doesn't know that new elements have appeared.

post.component.ts

ngAfterViewInit(){  
  (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.4";

    if (d.getElementById(id)){
      //if <script id="facebook-jssdk"> exists
      delete (<any>window).FB;
      fjs.parentNode.replaceChild(js, fjs);
    } else {
      fjs.parentNode.insertBefore(js, fjs);
    }
  }(document, 'script', 'facebook-jssdk'));
}

Notice the if/else block in particular. We first remove the window variable FB, since facebook checks for its existence on script load. Then we call replaceChild to force the script to reload. (Also, it is necessary to include #xfbml=1&version=v2.4 at the end of the sdk url.)

Finally, place this HTML snippet where you'd like the comments to appear:

post.html

<div id="fb-root"></div>  
<div class="fb-comments" [attr.data-href]="insertUrlHere" data-numposts="20"></div>  

(attr.data-href allows you to use a variable instead of a hardcoded url. Else, use the data-href tag.)

For reference, take a look at our app GIFGAG, which allows users to comment on each GIF.

Ionic

There is a caveat with Ionic - the default in-app browser doesn't work nicely with Facebook's login, and will result in a blank page. We must handle the login flow ourselves before the comment page is shown. Luckily, Ionic Native's in-app browser supports caching. So, if users log in before the above script runs, they will be able to comment directly.

First, install Ionic Native In-App Browser:

$ ionic cordova plugin add cordova-plugin-inappbrowser
$ npm install --save @ionic-native/in-app-browser

An example of how you can use the browser:

onFbAuthStart(): Promise<any> {  
    return new Promise((resolve, reject) => {
      const authUrl = `https://www.facebook.com/v2.9/dialog/oauth/?client_id=${appId}&redirect_uri=${myLandingPage}`;
      const browser = this._iaBrowser.create(authUrl, '_blank', 'location=yes, toolbar=no');

      browser.on('loadstop')
        .takeUntil(browser.on('exit'))
        .subscribe(event => {

          if (!event.url.match('facebook.com')) {
            if (event.url.match('error')) {
              reject();
            } else {
              this.onFbAuthSuccess();
              resolve();
            }
            browser.close();
          }

        });

      browser.on('exit').first().subscribe(() => reject());
    });
  }

After the Promise resolves, you can navController.push the appropriate comments page.