Is it possible to post on page as page via FB.api ?
I know how to post as page administrator, but to post as page, we have to use page access token. But I don't know how to call FB.api with page access token.
Try this one:
FB.login(function(response) {
FB.api('/me/accounts', function(apiresponse) {
var data = apiresponse['data'];
var ids = new Array();
for (var i = 0; i < data.length; i++) {
ids[i] = data[i].id;
}
console.log(ids);
});
}, { scope: 'manage_pages,publish_pages' });
Related
So my app just open a new window of a local html file with a webview tag of some webpage. But when I tried to get the cookies, I cannot get anything.I think the reason is the cookie is bounded to the url of the webview tag but now my local file but when I can only get the window of the local file.How can I solve this problem?
it might be late but i will answer this for future visitors :P
I think the best and the direct way to set and get cookies without any workarounds is to use webview request interceptors and change the request and response headers this is more secure and reliable and will work in nodewebkit, electron and chromium extensions and apps:
So to set headers you can use onBeforeSendHeaders,
for example lets say you want to change a cookie called "connect.sid" that used as session id in expressjs you can do the following:
var new_sessionId = "s%randskbksbdfmnsdbf345k345h34k5";
var $webview = $("#my-webview");
$webview.get(0).request.onBeforeSendHeaders.addListener(
function (details) {
details.requestHeaders.forEach(function (header) {
if (header.name === "Cookie") {
var cookies = header.value.split("; ");
var valid_cookies = cookies.filter(function (cookie) {
return cookie && cookie.indexOf("connect.sid") < 0;
});
valid_cookies.push("connect.sid=" + new_sessionId);
header.value = valid_cookies.join("; ");
}
});
return {requestHeaders: details.requestHeaders};
},
{urls: ["<all_urls>"]},
["blocking", "requestHeaders"]
);
$webview.attr("src","http://example.com");
and to read headers you can use onHeadersReceived
var $webview = $("#my-webview");
$webview.get(0).request.onHeadersReceived.addListener(function (details) {
details.responseHeaders.forEach(function (header) {
if (header.name === "set-cookie") {
var cookies = header.value.split("; ");
var sessionCookie = cookies.find(function (cookie) {
return cookie && cookie.indexOf("connect.sid") === 0;
});
if (sessionCookie) {
var sessionId = sessionCookie.split("=")[1];
console.log(sessionId);
}
}
});
},
{urls: ["<all_urls>"]},
["blocking", "responseHeaders"]
);
$webview.attr("src","http://example.com");
Note: you can also set and get cookies for your main window using this method but instead of intercepting webview.request you can intercept chrome.webRequest or just use chrome.cookies.set and chrome.cookies.get, i found all these things in chromium source code ;)
I want to create an app using restfb to get all the posts and comments on those post of any page. I was able to do so using user access token but with app access token I can get only the posts and not comments on them. What could be the reason for this?
Following code worked with user access token to get both posts and comments, but with app token, it doesn't give comments.
Page page = facebookClient.fetchObject("lockheedmartin", Page.class);
System.out.println(page.getIsVerified());
System.out.println("bio: "+page.getCategory());
int totalResults = 0;
Connection<Post> pageFeed = facebookClient.fetchConnection(page.getId() + "/feed", Post.class,Parameter.with("limit", 20));
for (List<Post> feed : pageFeed) {
totalResults = totalResults + feed.size();
for (Post post : feed) {
com.restfb.types.Post.Comments comments = post.getComments();
if(comments !=null){
List<Comment> commentList = comments.getData();
for(Comment comment : commentList){
System.out.println(comment.getMessage());
}
}
}
}
So I had to use post's id to fetch the comments.
Page page = facebookClient.fetchObject("lockheedmartin", Page.class);
int totalResults = 0;
Connection<Post> pageFeed = facebookClient.fetchConnection(page.getId() + "/feed", Post.class,Parameter.with("limit", 20));
for (List<Post> feed : pageFeed) {
totalResults = totalResults + feed.size();
for (Post post : feed) {
Connection<Comment> comments = facebookClient.fetchConnection(post.getId()+ "/comments", Comment.class);
if(comments !=null){
List<Comment> commentList = comments.getData();
for(Comment comment : commentList){
System.out.println(comment.getMessage());
}
}
}
}
The Page is most likely restricted by age or location, so you MUST use a User or Page token. An App Token does not have any relation to a User, so Facebook does not know if you are allowed to see the content.
More information about Tokens:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
I've been working on the famo.us Slideshow tutorial and realised that the API is no longer working.
Any ideas how can I still make this to work without the Picasa API?
You can keep the API by using the following code for SlideData.js
You can make it work by creating the objects returned by the url + parameters below and returning them as the JSON object if you do not want to use the API.
define(function(require, exports, module) {
var SlideData = {
picasaUrl: 'https://picasaweb.google.com/data/feed/api/all',
queryParams: '?kind=photo&q=puppy&max-results=5&imgmax=720&alt=json',
defaultImage: 'https://lh4.googleusercontent.com/-Roszbra0TlI/VB-fE83NAXI/AAAAAAAAACU/ITmhyZMHZrk/s720/cute%252520looking%252520white%252520and%252520black%252520french%252520Bulldog%252520Puppy.jpg'
};
SlideData.getUrl = function() {
return SlideData.picasaUrl + SlideData.queryParams;
};
SlideData.parse = function(data) {
var urls = [];
data = JSON.parse(data);
var entries = data.feed.entry;
for (var i = 0; i < entries.length; i++) {
var media = entries[i].media$group;
urls.push(media.media$content[0].url);
}
return urls;
};
module.exports = SlideData;
});
Currently, I am trying to solve a bug logged in Facebook Developer:
https://developers.facebook.com/bugs/325086340912814/
I am using ASP.NET MVC 3 with Facebook C# SDK and Facebook Javascript SDK.
Here is javascript code:
window.fbAsyncInit = function () {
// init the FB JS SDK
FB.init({
appId: '298365513556623', // App ID from the App Dashboard
channelUrl: 'http://www.christianinfoportal.com/channel.html', // Channel File for x-domain communication
status: true, // check the login status upon init?
cookie: true, // set sessions cookies to allow your server to access the session?
xfbml: true // parse XFBML tags on this page?
});
// Additional initialization code such as adding Event Listeners goes here
FB.Event.subscribe('auth.authResponseChange', function (response) {
if ((response.status == 'connected')) {
if (fbIgnoreFirstEventFire)
fbIgnoreFirstEventFire = false;
else {
// 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;
// TODO: Handle the access token
// Do a post to the server to finish the logon
// This is a form post since we don't want to use AJAX
var form = document.createElement("form");
form.setAttribute("method", 'post');
form.setAttribute("action", '/FBLogin');
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'accessToken');
field.setAttribute("value", accessToken);
form.appendChild(field);
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'returnUrl');
field.setAttribute("value", window.location.href);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
}
} 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.
}
});
};
// Load the SDK's source Asynchronously
(function (d, debug) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
ref.parentNode.insertBefore(js, ref);
}(document, /*debug*/ false));
The View code is pretty simple:
<div id="fbLoginButton" class="fb-login-button" data-show-faces="false" data-width="50" data-max-rows="1" data-scope="email"></div>
I basically forward the access token to a server side code page:
public ActionResult FBLogin(String returnUrl)
{
var accessToken = Request["accessToken"];
//FB fires even without the user clicking the Log In button
Session["FBLoginFirstClick"] = true;
//Session["AccessToken"] = accessToken;
//this.lblAccessToken.Text = accessToken;
//Response.Redirect("/MyUrlHere");
var client = new Facebook.FacebookClient(accessToken);
dynamic me = client.Get("me");
String email, fullName;
fullName = me.first_name + " " + me.last_name;
email = me.email;
Models.User.ThirdPartyLogin(email, fullName, Session);
if (!string.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
Solved by using Facebook authentication redirect.
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/
I am using jquery tool for tab Ui,
Now I want to keep tab selected on page reload. Is there any way to do that? below is my code
$(function() {
// setup ul.tabs to work as tabs for each div directly under div.panes
$("ul.tabs").tabs("div.panes > div");
});
Here is a simple implementation of storing the cookie and retrieving it:
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
Then, to save/retrieve cookie data with jQuery UI Tabs:
$(function() {
// retrieve cookie value on page load
var $tabs = $('ul.tabs').tabs();
$tabs.tabs('select', getCookie("selectedtab"));
// set cookie on tab select
$("ul.tabs").bind('tabsselect', function (event, ui) {
setCookie("selectedtab", ui.index + 1, 365);
});
});
Of course, you'll probably want to test if the cookie is set and return 0 or something so that getCookie doesn't return undefined.
On a side note, your selector of ul.tabs may be improved by specifying the tabs by id instead. If you truly have a collection of tabs on the page, you will need a better way of storing the cookie by name - something more specific for which tab collection has been selected/saved.
UPDATE
Ok, I fixed the ui.index usage, it now saves with a +1 increment to the tab index.
Here is a working example of this in action: http://jsbin.com/esukop/7/edit#preview
UPDATE for use with jQuery Tools
According the jQuery Tools API, it should work like this:
$(function() {
//instantiate tabs object
$("ul.tabs").tabs("div.panes > div");
// get handle to the api (must have been constructed before this call)
var api = $("ul.tabs").data("tabs");
// set cookie when tabs are clicked
api.onClick(function(e, index) {
setCookie("selectedtab", index + 1, 365);
});
// retrieve cookie value on page load
var selectedTab = getCookie("selectedtab");
if (selectedTab != "undefined") {
api.click( parseInt(selectedTab) ); // must parse string to int for api to work
}
});
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays === null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
Here is a working (unstyled) example: http://jsbin.com/ixamig/12/edit#preview
Here is what I see in Firefox when inspecting the cookie from the jsbin.com example:
This is what worked for me... at least I haven't run into any issues yet:
$('#tabs').tabs({
select: function (event, ui)
{
$.cookie('active_tab', ui.index, { path: '/' });
}
});
$('#tabs').tabs("option", "active", $.cookie('active_tab'));
I'm using: jQuery 1.8.2, jQuery UI 1.9.1, jQuery Cookie Plugin.
I set the "path" because in C# I set this value in a mvc controller which defaults to "/". If the path doesn't match, it wont overwrite the existing cookie. Here is my C# code to set the value of the same cookie used above:
Response.Cookies["active_tab"].Value = "myTabIndex";
Edit:
As of jQuery UI 1.10.2 (I just tried this version, not sure if it's broken in previous versions), my method doesnt work. This new code will set the cookie using jQuery UI 1.10.2
$('#tabs').tabs({
activate: function (event, ui) {
$.cookie('active_tab', ui.newTab.index(), { path: '/' });
}
});
The easiest way to survive between page refresh is to store the selected tab id in session or through any server-side script.
Only methods to store data on client side are: Cookies or localStorage.
Refer to thread: Store Javascript variable client side