I am trying to figure out how can I get to know if a user shares a link to his feed selecting only me as an option. I want to know this because if the user shares my link to himself then the promotion of my website won't be possible.
<div id="fb-share">Share</div>
<div class="social-share-wrap"></div>
jQuery('#fb-share').on('click', function() {
checkLoginState();
});
function statusChangeCallback(response) {
console.log(response);
if (response.status === 'connected') {
shareUrl();
} else if (response.status === 'not_authorized') {
checkLoginState();
} else {
checkLoginState();
}
};
function checkLoginState() {
FB.login(function (response) {
console.log(response);
statusChangeCallback(response);
}, {scope: 'email'});
};
function shareUrl() {
FB.ui({
method: 'feed',
link: 'http://www.example.com',
}, function(response) {
if (response && response.post_id) {
FB.api('/me', function (response) {
jQuery.post('test.php',{name: response.name, email: response.email}).done(function(data) {
jQuery('.social-share-wrap').html(data);
jQuery.fancybox({
href: '#social-share',
centerOnScroll: true,
hideOnOverlayClick: false
});
return false;
});
});
} else {
console.log('cancelled by user');
}
});
};
In the above code what I'm doing is when a user clicks the share div the user gets the login popup and then the user gets the permission popup and then the share iframe appears now if the user shares successfully his info is posted to test.php and if the user cancels it gets logged in console. I did not find anything in the api where I can get to know if user selects custom and sets it to only me.
You can´t check the permission setting, it´s completely up to the user and there is no way to detect which one he selected. After all, you are not allowed to incentivize sharing according to the platform policy, so it´s not really relevant to know.
Related
I'm using Facebook login in the simplest way, and getting a call back response:
<div id="fb-root"></div>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v6.0&appId=881911462250499&autoLogAppEvents=1"></script>
<script>
window.fbAsyncInit = function() {
FB.getLoginStatus(function(response) {
FB.api('/me', function (response) {
console.log(response);
});
});
}
</script>
I log the response to the console and receive the name and id, but not email address. How can I get the email as well? Upon researching it, it should get it by default, am I wrong?
According to the Fb docs, This is how you do it.
function statusChangeCallback(response) { // Called with the results from FB.getLoginStatus().
console.log('statusChangeCallback');
console.log(response); // The current login status of the person.
if (response.status === 'connected') { // Logged into your webpage and Facebook.
testAPI();
} else { // Not logged into your webpage or we are unable to tell.
document.getElementById('status').innerHTML = 'Please log ' +
'into this webpage.';
}
}
window.fbAsyncInit = function() {
FB.init({
appId : '{app-id}',
cookie : true, // Enable cookies to allow the server to access the session.
xfbml : true, // Parse social plugins on this webpage.
version : '{api-version}' // Use this Graph API version for this call.
});
FB.getLoginStatus(function(response) { // Called after the JS SDK has been initialized.
statusChangeCallback(response); // Returns the login status.
});
};
function testAPI() { // Testing Graph API after login. See statusChangeCallback() for when this call is made.
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
});
}
You can check login status in this way.
function checkLoginState() { // Called when a person is finished with the Login Button.
FB.getLoginStatus(function(response) { // See the onlogin handler
statusChangeCallback(response);
});
}
By default, fb allows only basic permissions. What you require is additional permission, hence you have to request it this way.
FB.login(function(response) {
// handle the response
}, {scope: 'email,user_likes'});
You can read more about it here. Hope it helps :)
Ok got it, I was confused and it shoudl be here:
FB.api('/me', { locale: 'tr_TR', fields: 'email,name' }, function (response) {
Facebook sharing using feed or share has a success call back and can tell if user shared or not, but when using iframe it allways says that the user canceled the dialog {error_code: 4201, error_message: "User+canceled+the+Dialog+flow"}and cant tell if the user shared or not, but same function without the use of iframe is working properly
function sharfeToFacebook() {
var deferred = $q.defer();
var options = {
method: 'share',
mobile_iframe: true,
href: photoUrl,
};
FB.ui(options, function(response) {
console.log('FB share dialog started with response: ', response);
if (response && !response.error_code) {
// fb does returns an emtpy object on success, undefined when fail or canceled
deferred.resolve(response);
} else {
deferred.reject(response);
}
});
}
return deferred.promise;
I'm using the documentation provided over here with the following code. The share dialog comes up correctly. The problem is that I'm not able to differentiate between "Cancel" and "Post" actions that the user takes on the dialog. I'd imagine this would be a part of the response.
FB.ui({
method: 'share',
href: 'https://developers.facebook.com/docs/',
}, function(response){
if (response && !response.error_code) {
console.log(response);
} else {
alert('Error while posting.');
}
});
edit: output from the console isn't doesn't provide any way of knowing
Cancel - Object {e2e: "{"submit_0":1401181811121}"}
Post - Object {e2e: "{"submit_0":1401181815112}"}
I tested this, and apparently there's some info in the response object you could use to determine if the dialog was cancelled.
Code
FB.ui({
method: 'share',
href: 'https://developers.facebook.com/docs/'
}, function(response){
if (response && !response.error_code) {
console.log("OK: "+JSON.stringify(response));
} else {
console.log("Not OK: "+JSON.stringify(response));
}
});
Output upon cancellation:
{error_code: 4201, error_message: "User+canceled+the+Dialog+flow", e2e: "{"submit_0":1401188820613}"}
So, I guess you could check for cancellaction like this:
FB.ui({
method: 'share',
href: 'https://developers.facebook.com/docs/'
}, function(response){
if (response && !response.error_code) {
console.log("OK: "+JSON.stringify(response));
} else if (response && response.error_code === 4201) { //Cancelled
console.log("User cancelled: "+decodeURIComponent(response.error_message));
} else {
console.log("Not OK: "+JSON.stringify(response));
}
});
Unfortunately, FB.Events.subscribe() doesn't offer an Event for the Cancallation of this dialog: https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/v2.0
This is intentionally so as to dissuade developers from using posting as a gating mechanism. It should be up to the person to choose whether to post or not, it should not be a requirement of the app.
Use "feed" method instead of "share" so that it doesn't require app permission to get the response.
FB.ui({
method: 'feed',
caption: 'My Caption',
link: 'http://www.google.com/'
}, function(response) {
if (response && response.post_id) {
alert('Thank you for sharing!');
} else {
alert('You have cancelled the share.');
}
});
I also have a problem with the response function, I'm currently coding and trying to use fb.UI
return FB.ui({
method: 'share',
href: this.shareUrl,
hashtag: "myHashTag",
quote: "myQuote"
}, function(res) {
console.log("res = ", res);
console.log("res? = ", res != null);
return App.vent.trigger("FBShareView:cancelled");
});
I'm finding that on a successful share, res is an empty array and res != null is true
I'm finding that for the cancel scenario, res is undefined.
I expected to see res as an object with an error_message as described here: https://developers.facebook.com/docs/sharing/reference/share-dialog
Could you tell me what may be going wrong please?
I'm working with jQuery Mobile.
My Code for move to details div ::
Go To Details
Now, I want to authenticate user with Facebook.
So I have applied ::
Login with Faceook
Function Calling for Authentication
function userLogin() {
FB.login(
function(response) {
if (response.authResponse) {
alert('logged in');
FB.api('/me', function(response) {
alert("Welcome " + response.name);
});
} else {
alert('not logged in');
}
},
{ scope: "email" }
);
}
I'm getting valid user response after authentication.Now I want to navigate to that details div.
So, how can I implement that ajax code after successfully login ??
Any suggestion will be appreciated.
Thanks.
Instead of changing the href attribute directly, you should bind the onclick event to a function returning true.
Modify your a tag.
Go To Details
Modify your userLogin function:
function userLogin() {
FB.login(
function(response) {
if (response.authResponse) {
alert('logged in');
FB.api('/me', function(response) {
alert("Welcome " + response.name);
});
} else {
alert('not logged in');
}
},
{ scope: "email" }
);
return true;
}
It seems that FB.login is an asynchronized operation. If you want to redirect after the login action, try to modify the location.hash after login. Note that the return value has changed to false.
function userLogin() {
var hash = '#details';
FB.login(
function(response) {
if (response.authResponse) {
alert('logged in');
FB.api('/me', function(response) {
alert("Welcome " + response.name);
window.location.hash = hash;
});
} else {
alert('not logged in');
}
},
{ scope: "email" }
);
return false;
}
Use $.ajax() for making a call to the Facebook API to authenticate and in the callback function of the ajax function, call the click event of the details link.
Maybe something like this,
$.ajax({
url : 'https://graph.facebook.com/me'+whatever,
success : function(){
$('#details').click()
}
});
The success function will be called when the ajax call is successful.
I would like to use fb.api to post on logged user, but just once. If I put this
var params = {};
params['message'] = 'gegeegeggegall! Check out www.facebook.com/trashcandyrock for more info.';
params['name'] = 'gegeggeeg - gegegege';
params['description'] = 'Check out Tegegegeg! Win merch by playing and reccomending to your friends.';
params['link'] = 'http://www.bblblba.com';
params['picture'] = 'http://summer-mourning.zoocha.com/uploads/thumb.png';
params['caption'] = 'Tgegegegeeg';
FB.api('/me/feed', 'post', params, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Published to stream - you might want to delete it now!');
}
});
It posts to users wall everytime he refreshes the site?
What to do?
What is triggering the FB.api call? If it's just code within a tag then it's going to run as soon as the browser gets to that point.
You could possibly store some sort of cookie value or something after the FB.api call then check it on page load, but that seems like more work than is probably needed.
Do you want him to post it only once, ever?
If so, you're going to need to create a "state". In order to do this, you could do it client sided (with cookies), or server sided (with a database).
Create a boolean variable named "posted", and store it in a cookie or in a database (since you're using javascript, it's probably easier to use a cookie).
var posted=getCookie("posted");
if(!posted)
{
//call the FB.api();
setCookie("posted", true, duration);
}
Definition of setCookie and getCookie: http://www.w3schools.com/JS/js_cookies.asp
You could run a FQL query and check to see if the message has already been posted by querying the stream table with your app id. Something like:
<!DOCTYPE html>
<html>
<body>
<div id="fb-root"></div>
Post To Wall
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({ appId : '**yourAppID**', status : true, cookie : true, xfbml : true });
function postToWall() {
FB.login(function(response) {
if (response.session) {
FB.api(
{
method: 'fql.query',
query: 'SELECT post_id, message from stream where app_id = **yourAppID** and source_id = me()'
},
function(response) {
if(response.length == 0){
FB.ui(
{
method: 'feed',
name: 'Facebook Dialogs',
link: 'https://developers.facebook.com/docs/reference/dialogs/',
picture: 'http://fbrell.com/f8.jpg',
caption: 'Reference Documentation',
description: 'Dialogs provide a simple, consistent interface for applications to interface with users.',
message: 'Facebook Dialogs are easy!'
},
function(response) {
if (response && response.post_id) {
alert('Post was published.');
} else {
alert('Post was not published.');
}
}
);
}
else {
alert('User already posted this message');
}
}
);
}
} , {perms:''});
}
</script>
</body>
</html>