비바라기's
[FB API] Uncaught ReferenceError: FB is not defined when using FB.getLoginStatus 본문
TIL/기타
[FB API] Uncaught ReferenceError: FB is not defined when using FB.getLoginStatus
vivaragi 2022. 8. 28. 13:30<div id="fb-root"></div>
<script>
window.fbAsyncInit = function () {
FB.init({
appId: '######', // App ID
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
};
// Load the SDK Asynchronously
(function (d) {
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
</script>
위와 같은 코드를 실행하면 Uncaught ReferenceError: FB is not defined when using FB.getLoginStatus 와 같은 에러가 발생합니다. window.fbAsyncInit 내부의 FB.init이 실행되기 전에 FB를 참조, FB.getLoginStatus를 실행하고 있기 때문입니다(호이스팅).
해결 방법은 두 가지가 있습니다. 하나는 window.fbAsyncInit 내부, FB.init 아래에 FB.getLoginStatus 코드를 추가하는 것입니다. 하지만 이 방법은 다소 직관적이지 않습니다. 두번째 방법은 아래와 같이 임의의 함수(fbload)를 window.fbAsyncInit 외부에 정의하는 대신, $(document).trigger("새로 정의한 함수명")과 같은 코드를 FB.init 아래에 추가하는 것입니다. $(document).trigger 는 새로 정의한 함수들(여기선 fbload)를 순서에 맞춰 강제로 실행시킵니다. 1
window.fbAsyncInit = function() {
FB.init({
appId : '123456789',
status : true,
cookie : true,
xfbml : true
});
$(document).trigger('fbload'); // <---- THIS RIGHT HERE TRIGGERS A CUSTOM EVENT CALLED 'fbload'
};
$(document).ready(function(){
$(document).on(
'fbload', // <---- HERE'S OUR CUSTOM EVENT BEING LISTENED FOR
function(){
FB.getLoginStatus(function(res){
if( res.status == "connected" ){
FB.api('/me', function(fbUser) {
console.log("Open the pod bay doors, " + fbUser.name + ".");
});
}
});
}
);
});
'TIL > 기타' 카테고리의 다른 글
[FB API] Facebook Login API를 http에서 개발하고 싶을 때 (0) | 2022.08.28 |
---|---|
[JS] $(document).on은 되는데 $(”#id”).on은 안될 때 (0) | 2022.08.28 |