Extracting page id from a facebook page url - javascript

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.

Related

Update history state and redirect

How can I update the history state and then redirect to a new page so that the back button returns to the updated history.
ie:
I go to search.html?query=test
Update history to search.html?waitQuery=test
Redirect to Google search "test"
Hit back button, go to search.html?waitQuery=test
For context: At my work site we use a ticketing system and to speed up my workflow I've created a local script file and set it as a custom search engine in Chrome. It uses regular expressions to check if a query matches a ticket ID pattern and if so will redirect to the ticket system, and if not redirects to Google.
This way if I search something like "TK00123" in the address bar, it redirects to http://ticketengine/query?TK00123 but if I search "hello world" it just forwards that query to Google.
I would like to be able to hit the back button after the redirect and get a sort of interstitial page where I could choose from some options.
This is what I have currently:
<script>
let ticketSearch = 'http://ticketengine/query?'
let googleSearch = 'https://www.google.com/search?q='
if (location.search.match(/\?query=(.+)/)) {
let searchQuery = RegExp.lastParen
history.pushState({}, '', location.pathname + '?waitQuery=' + RegExp.lastParen)
if (searchQuery.match('TK\d+')) {
location.href = ticketSearch + searchQuery
} else {
location.href = googleSearch + searchQuery
}
} else if (location.search.match(/\?waitQuery=(.+)/)) {
let searchQuery = RegExp.lastParen
document.write(`Ticket: ${decodeURIComponent(searchQuery)}<br>`)
document.write(`Google: ${decodeURIComponent(searchQuery)}<br>`)
}
</script>
From everything I've read this seems like it should work, but I never actually get that history entry that I can go back to. The redirect wipes it out.

Add URl to cookie and redirect to URL on return

I need to check if a cookie is present in order to let a user continue on their journey, if it's not they click a button (which then sets the cookie) and fires them off to a third party to register some details before returning.
I can set and check for the cookie but I'd like to add the page url to the cookie and when the user returns from the third party site the url in the cookie is picked up and they're redirected to the page they left from. (Hope that all makes sense).
Code so far...
//Check for cookie
if (document.cookie.indexOf("LostForWordsSession=Valid") == -1) {
$('.poster-image').show(); // This is a button that's shown if the cookie isn't present
}
// Button code
var url = window.location.href;
$(".poster-image").click(function(){
document.cookie = "LostForWordsSession=Valid; path=url";
window.location.replace("off to another site to register");
});
Once the user has registered they will be forwarded to a generic page on my site from where I'd like to redirect them (no code for that yet as I'm a bit stumped).
Any help really appreciated! And thanks in advance =)
This sounds like a job for sessionStorage:
// I assume you want to go to the old URL?
// this code needs to be in all pages you can return to from rd party
const url = window.location.href;
const session = sessionStorage.getItem("LostForWordsSessionUrl");
if (session && session != url) location.replace(session);
else session = false;
$('.poster-image').toggle(!session); // show if no session
$(".poster-image").on("click",function(){
sessionStorage.setItem("LostForWordsSessionUrl",url)
window.location.replace("off to another site to register");
});

chrome extension and Facebook login problems

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...
}
}
}
});

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.

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);
}})();

Categories

Resources