chrome extension and Facebook login problems - javascript

I try to write a chrome extension which is triggered by visting a certain website. So far this works already. My extension users are from my web game where they login with their facebook account. For identifying the extension users with their game account I need to know their fb app scoped user id from my game.
So far I learned my background script is not able to use the facebook sdk for login because window.fbAsyncInit isn't called inside. I looked around for solutions and I found this page: http://brianmayer.com/2012/12/building-a-chrome-extension-that-connects-to-a-facebook-app/
He opens an invisible tab that contains an iframe. Inside of the iframe he calles the facebook login sdk from the webserver and then sends the user data with windows.postmessage to the parent. That sounds like the perfect solution for my problem. There is only one line that I don't understand what I have to add there:
parent.postMessage({connectStatus:"" + response.status + "", userID:"" + uid + "", accessToken:"" + at + ""}, "https://www.<PARENT_PAGE_DOMAIN>"); //This MUST match the root domain where the iFrame will be inserted, or the message won't get passed
What do I have to add in the field PARENT_PAGE_DOMAIN? I used the root domain of the page which is in the content_scripts/maches in the manifest file and I used the domain where the iframe page is hosted but I never receive the message in my background script

Did you try use this ?
enter link description here
First of all you need to get redirect url
Here is my code:
chrome.identity.launchWebAuthFlow({
url: AUTH_URL,
interactive: true
}, function(redirectURL) {
if (chrome.runtime.lastError) {
alert(chrome.runtime.lastError.message);
}
if(redirectURL){
var q = redirectURL.substr(redirectURL.indexOf('#')+1);
var parts = q.split('&');
for (var i = 0; i < parts.length; i++) {
var kv = parts[i].split('=');
if (kv[0] == 'access_token') {
var token = kv[1];
console.log(token)
// do something...
}
}
}
});

Related

URL routing not working when user clicks a link

I am trying to modify a web application we have and I'm not sure if I can do what is being requested. My boss wants to be able to click a link from an email and have our internal company web application go straight to a page identified at the end of a provided URL.
If I click on the link below the first time, it goes to the index page of our web application. If I leave the web application open and click on the link again, it goes to the correct page identified at the end of the URL.
http://mycompanyweb.com/handbook/mycompanyprocess/#/rt/softwate/9.13_UpdateSDP
I've tried adding an init(), thinking that is where the application goes first in the lifecycle and I only see this part of the URL at that point (http://mycompanyweb.com/handbook/mycompanyprocess/). This leads me to believe that the browser is stripping everything off after the # when it first opens. Is that correct? Is there something I can do to get our web application to go directly to the document the first time a user clicks on the link, without the web application open?
http://mycompanyweb.com/handbook/mycompanyprocess/ - Base URL
#/rt - Used by our javascript engine to determine which path to take
(dev or production).
/software/9.13_UpdateSDP - Logical path to a web page named 6.034_UpdateSDP.htm
Our engine that determines where to route based on the URL. I assume that the second time a link is clicked that it goes to the correct page is because the engine has been loaded (provided the browser is left open when clicked a second time).
$(document).ready(function () {
// Define the routes.
Path.map("#/:program").to(function () {
var program = this.params['program'];
if (program == "search") {
$("#mainContent").load("search.html");
}
else {
$("#mainContent").load("views/onepageprocess.html");
}
$("#subheader").html("");
$("#headerLevelTwoBreadcrumbLink").html("");
}).enter(setPageActions);
Path.map("#/:program/:swimlane").to(function () {
localStorage.removeItem("SearchString");
var swimlane = this.params['swimlane'];
var view = "views/" + swimlane + ".html";
$("#mainContent").load(view);
}).enter(setPageActions);
// Sends all links to the level three view and updates the breadcrumb.
Path.map("#/:program/:swimlane/:page").to(function () {
var page = this.params['page'];
var url = "views/levelthree/" + page.replace("", "") + ".htm";
var levelThreeTitle = "";
$.get(url)
.done(function () {
// Nothing here at this time...
}).fail(function () {
url = "views/levelthree/badurlpage.htm";
levelThreeTitle = "Page Unavailable";
}).always(function (data) {
$("#subheader").html("");
level_three_breadcrumb = "views/breadcrumbs/breadcrumb_link.html";
$("#headerLevelTwoBreadcrumbLink").load(level_three_breadcrumb);
$("#headerLevelThreeBreadcrumb").html("");
$('#headerLevelThreeBreadcrumb').append('<img src="images/Chevron.gif" />');
if (data.status != "404") {
$("#headerLevelThreeBreadcrumb").append(retrieveStorageItem("LevelThreeSubheader"));
}
$("#mainContent").load(url);
});
}).enter(setPageActions);
// Set a "root route". User will be automatically re-directed here. The definition
// below tells PathJS to load this route automatically if one isn't provided.
Path.root("#/rt");
// Start the path.js listener.
Path.listen();
});
Is there something I can do to get our web application to go directly to the document the first time a user clicks on the link, without the web application open?
If anyone runs into something like this, I found out that my company's servers were stripping anything after the # in the URL at authentication. I will be modifying my app to not use hash tags in the URL to fix it.

Extracting page id from a facebook page url

I have an application where when a user enters their facebook fan page url, I extract the page id and store that into the database to be used later in facebook graph api.
I have added the following js to extract page id:
<script>
var fburl= "https://www.facebook.com/audi";
if(fburl.indexOf("?") != -1) {
var fburl_new=fburl.split("/");
var fburl_newer=(fburl_new[fburl_new.length-1])
var fburl_newer =fburl_newer.split("?");
var fbnameonly=(fburl_newer[fburl_newer.length-2]);
} else {
var fbnameonly = fburl.substring(fburl.lastIndexOf('/') + 1);
}
if(fbnameonly==undefined) {
console.log(fburl);
}else {
console.log(fbnameonly);
}
</script>
So, if I a user enters a facebook url like: https://www.facebook.com/audi, I get the output audi which is fine.
If a user enters facebook url as : https://www.facebook.com/pages/abc-def/1234568, I get the output 1234568 which is fine.
but for urls like:
https://www.facebook.com/abc-def-12345678/ (should return 12345678)
or
https://www.facebook.com/audi/timeline?ref=page_internal (should return audi)
I am unable to get the page id, is there any better way by which I can extract page id from any facebook fan page url and use it in facebook graph api like: https://graph.facebook.com/page_id dynamically ?
I figured out a better way to get page id from any facebook page url, I am not sure if there is even better option to do this but here is the code what I have used:
$fbUrl = "https://www.facebook.com/Lo-stile-di-Anna-1521824524722026";
$graphUrl = "https://graph.facebook.com/?id=".$fbUrl."&access_token=xxxxx&fields=id";
$output = file_get_contents($graphUrl);
$output = json_decode($output, TRUE);
echo $output["id"]; // returns 1521824524722026
I tried this with various facebook urls and it worked everytime, hope this helps someone in the future.

How do I distribute my bookmarklet conveniently?

I just wrote my first bookmarklet. It is simple js code which takes the current page's URL and does a POST request to submit it to another page.
The problem is that I need to share this on a blogging platform (quora.com) that does not allow HTML. Thus, I need to post a link to my bookmarklet on a different website and provide a link to that. I'd like to be able to provide a single link that folks can drag to their bookmarks bar.
This is the bookmarklet code.
javascript:(function() {
var msg = window.jQuery.ajax({url:'https://www.quora.com/api/logged_in_user',async:false,type:'GET'});
var username = undefined;
if (msg) {
username = window.jQuery.parseJSON(msg.responseText.replace('while(1);',''));
window.jQuery.post('https://my-website',
{'answer_1':window.location.href,'submitter':username.name});
alert (username.name + ' nominates ' + window.location.href);
}})();

How to get access token from node-webkit for a desktop app without hosting page?

I'm trying to create a desktop app with node-webkit. A part of this app require the use of facebook to get/post some content to any profile (facebook user) that use my desktop app on my personal computer.
Regarding facebook api documentation (https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.0) , I have to manually implement the login flow and use the following URI as the redirect URI: https://www.facebook.com/connect/login_success.html
Currently, in my node-webkit app, via a child window (a popup), a user can login to facebook and authorize my desktop app to interact with it's profile.
Here is a part of the code:
var url = "https://www.facebook.com/dialog/oauth?client_id=myclientID&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=token&scope=publish_actions";
loginWindow = window.open(url, 'Login facebook', 'location=yes,toolbar=yes,menubar=yes,directories=yes,status=yes,resizable=yes,scrollbars=yes,height=480,width=640', false);
After that, the user is redirected to the following URI and as mentioned in the doc, the access token appear correctly:
https://www.facebook.com/connect/login_success.html#access_token=theBigTokenString&expires_in=3864.
But it appears only for few seconds and after that the url is replaced by https://www.facebook.com/connect/blank.html#_=_ (with a security warning message).
I've read some post that propose to add eventListener like hashchange to the opened window in order to capture the access token. But after some redirect within the child window, I'm no longer available to interact with it via javascript.
So finally, I can't get the access token that the child window has retrieved and make visible for few seconds.
Is anyone can help me to get this user access token with node-webkit?
I really don't want to use a server (for hosting a web page) between my desktop app and facebook.
Thanks in advance for help.
With the help of an other question (here) I found a solution to my problem.
I post the code that I use now and I Hope it will help someone else:
var url = "https://www.facebook.com/dialog/oauth?&client_id=myBigClientID&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=token&scope=publish_actions";
function Response() {
this.access_token = null;
this.expires_in = null;
};
var response = new Response();
//function called every 500ms to check if token is in url
window.hashUpdate = function() {
if(window.loginWindow.closed){
window.clearInterval(intervalId);
start(); //just a callback that I'm using to start another part of my application (after I caught the token)
}
else {
var url = window.loginWindow.document.URL;
var tabUrl = url.split("#"); //first split to separate the domain part and the parameter part
var paramString = tabUrl[1]; //I concerned only by the second part after the '#'
if(paramString != undefined){
var allParam = paramString.split("&");
for (var i = 0; i < allParam.length; i++) {
var oneParamKeyValue = allParam[i].split("=");
response[oneParamKeyValue[0]] = oneParamKeyValue[1]; //store my token in form of key => value
};
//close the window after 1500ms
setTimeout(function(){
window.loginWindow.close();
}, 1500);
}
}
}
//open the url and start the watching process
window.loginWindow = window.open(this.url, 'Login facebook', false);
this.intervalId = window.setInterval("window.hashUpdate()", 500);

Facebook Application permission

Hi I have developed a Facebook application in Flash using Action-script 3. The application is working fine. I have developed Facebook login and authentication in JavaScript. The problem is then the user is not sign in to Facebook the application works fine, provide the user login panel and application permission panel and post the desire thing on user wall but if the user is already sign in than the JavaScript wont ask for the Facebook app permission and hence the app wont post on user wall. My JavaScript code is
<script type="text/javascript">
var APP_ID = "xxxxxxxxxxxxxxx";
var REDIRECT_URI = "http://apps.facebook.com/engel-tanimiyorum/";
var PERMS = 'publish_stream , email, user_birthday'; //comma separated list of extended permissions
function init()
{
FB.init({appId:APP_ID, status: true, cookie: true, oauth: true});
FB.getLoginStatus(handleLoginStatus);
}
function handleLoginStatus(response)
{
if (response.authResponse && response.status=="connected")
{
//Show the SWF
$('#ConnectDemo').append('<h1>You need at least Flash Player 9.0 to view this page.</h1>');
swfobject.embedSWF("index.swf",
"ConnectDemo", "803", "516", "9.0", null, null, null, {name:"ConnectDemo"});
}
else
{
var params = window.location.toString().slice(window.location.toString().indexOf('?'));
top.location = 'http://graph.facebook.com/oauth/authorize?client_id='
+APP_ID
+'&scope='+PERMS
+'&redirect_uri=' + REDIRECT_URI
+ params;
}
}
$(init);
</script>
Yours quick response will be highly appreciable
Regards
I don't know if this helps or not. But instead of your
var PERMS = 'publish_stream , email, user_birthday';
I do believe it should be states as an Array and then you would list your permissions.
It works for me, so I think it should look like this:
public var PERMS:Array = ["publish_stream","email","user_birthday"];
Also, not having your variables public might be the problem too.
Also, from what I see, you don't have any buttons, or text input?
If not, you need to create those. Then have a click handler for when there is text in the text input it will activate a click handler that then will go to a submit post handler, which then goes to a get status handler that will show you the new status you have created. I may be saying this all wrong. After all, I am not using Java for my app. But it seems logical to me that that is what you would do.. Try my first suggestions out and get back to me. If you'd rather, email me at Shandan_Spencer#live.com, so I can help you some more.

Categories

Resources