我知道收到以下错误是一个常见问题:
ReferenceError:FB is not defined
我参考了下面的帖子,它似乎涵盖了一系列广泛的解决方案。FB未定义问题
特别是我遇到的问题是,如果我测试部署到浏览器的应用程序,fbAsyncInit(...)
会在我的根index.html
页面中命中。我之所以知道这一点,是因为我在FBinit代码的第一行放了一个alert('fbAsyncInit(..)')
。例如,如果我运行以下命令,它会提醒fbAsyncInit(..)
ionic serve
一旦我使用以下命令部署到设备,我就不会收到警报,当我试图实际调用$cordovaFacebook.login(...)
时,它会给我以下错误:
ReferenceError: FB is not defined
我的根index.html
看起来很相似(为了简洁起见,删除了一些内容)。
<html>
<!-- Other stuff here -->
<div id="fb-root"></div>
<script type="text/javascript" src="lib/additional/FacebookConnectPlugin.js"></script>
<script>
window.fbAsyncInit = function() {
console.log('fbAsyncinit(..)');
FB.init({
appId : '/*App id here*/',
cookie : true, // enable cookies to allow the server to access
xfbml : true, // parse social plugins on this page
version : 'v2.1' // use version 2.1
});
(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 = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
};
</script>
<!-- Other Stuff Here -->
</html>
它击中的一件事是FacebookConnectPlugin.js
中定义的以下代码
// Bake in the JS SDK
(function () {
if (!window.FB) {
console.log("launching FB SDK");
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/sdk.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
console.log(window.FB) //FB is undefined
}
}());
当为FacebookConnectPlugin.js
加载脚本标记并运行这段代码时,它会尝试将window.FB
打印到控制台,但未定义。
知道上面的代码出了什么问题吗?
您是否尝试过用准备好的文档包围您的脚本?
document.addEventListener("DOMContentLoaded", function(event) {
//do work
});
此外,我不建议你这样做。
你应该:
- 在应用程序上定义控制器
- 将$ionicPlatform就绪事件添加到控制器
- 在其中执行FB插件的初始化
您需要使用ngCordova,而不是传统方法。
http://ngcordova.com/docs/plugins/facebook/
样本代码
module.controller('MyCtrl', function($scope, $cordovaFacebook) {
$cordovaFacebook.login(["public_profile", "email", "user_friends"])
.then(function(success) {
// { id: "634565435",
// lastName: "bob"
// ...
// }
}, function (error) {
// error
});
var options = {
method: "feed",
link: "http://example.com",
caption: "Such caption, very feed."
};
$cordovaFacebook.showDialog(options)
.then(function(success) {
// success
}, function (error) {
// error
});
$cordovaFacebook.api("me", ["public_profile"])
.then(function(success) {
// success
}, function (error) {
// error
});
$cordovaFacebook.getLoginStatus()
.then(function(success) {
/*
{ authResponse: {
userID: "12345678912345",
accessToken: "kgkh3g42kh4g23kh4g2kh34g2kg4k2h4gkh3g4k2h4gk23h4gk2h34gk234gk2h34AndSoOn",
session_Key: true,
expiresIn: "5183738",
sig: "..."
},
status: "connected"
}
*/
}, function (error) {
// error
});
$cordovaFacebook.getAccessToken()
.then(function(success) {
// success
}, function (error) {
// error
});
$cordovaFacebook.logout()
.then(function(success) {
// success
}, function (error) {
// error
});
});