Last active
December 3, 2018 20:34
-
-
Save ThatGuySam/453e66768842cbf3410ba862d5a7ca7b to your computer and use it in GitHub Desktop.
Promise-based Facebook Javascript SDK for ES6 - React, Vue, etc...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
This a helper for adding Facebook's Javascript SDK in a modern development environment with build tools. | |
Runs as a promise so you can run: | |
await const FB = facebook() | |
OR | |
facebook().then((FB) => { | |
}) | |
and then know that your facebook SDK is initialized | |
It also should work with fullstack frameworks like Next.js and Nuxt.js | |
*/ | |
export default () => new Promise(function(resolve, reject) { | |
// Cancel if there's no document | |
if (typeof document !== 'object') reject('Is there a document?') | |
window.fbAsyncInit = function() { | |
console.log('Facebook SDK Initialized', window.FB) | |
const FB = window.FB | |
// Log a Page View | |
FB.AppEvents.logPageView() | |
resolve(window.FB) | |
} | |
const id = 'facebook-jssdk' | |
const fbAppId = process.env.FACEBOOK_APP_ID | |
if (document.getElementById(id)) reject('Facebook SDK already exists!') | |
// Create the fbScriptTag that we're going to add to the DOM later | |
const fbScriptTag = document.createElement('script') | |
// Find the first script tag present, we'll add the fbScriptTag before this | |
const anchorScriptTag = document.getElementsByTagName('script')[0] | |
// Set attributes | |
fbScriptTag.id = id | |
fbScriptTag.src = `https://connect.facebook.net/en_US/sdk.js#xfbml=0&version=v3.10&appId=${fbAppId}` | |
// Insert into DOM | |
if (typeof anchorScriptTag !== 'undefined') anchorScriptTag.parentNode.insertBefore(fbScriptTag, anchorScriptTag) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment