Redirect To my App if the app hosting site is visited - facebook

i want the codes which will redirect the user to my app if he/she tries to open my app hosting site.
for ex:
my app link: https://apps.facebook.com/gaming-zone/
app hosting link: http://gaming-zone.herokuapp.com/
i have found some codes already but those codes redirects the user continously and if he is using my app on facebook and he is playing any game then also it redirects the user to app home page.
i want the exact codes that redirect the user only when he visits my hosting site.
These are the codes that i found already:
<script type='text/javascript'>
if (window.top.location == window.location)
window.top.location = 'https://apps.facebook.com/gaming-zone/';
</script>

Here is the code that I use:
<script type="text/javascript">
function NotInFacebookFrame() {
return top === self;
}
function ReferrerIsFacebookApp() {
if(document.referrer) {
return document.referrer.indexOf("apps.facebook.com") != -1;
}
return false;
}
if (NotInFacebookFrame()) {
top.location.replace("https://apps.facebook.com/YOUR_APP_NAMESPACE");
}
</script>
This checks if they are currently in the Facebook frame and ONLY if they aren't it will redirect them to "https://apps.facebook.com/YOUR_APP_NAMESPACE"
Note: you can use this on any page in you app just change the URL accordingly.
For example: If you are using this in http://YourDomain.com/anotherpage.php you can change the URL in the code above to https://apps.facebook.com/YOUR_APP_NAMESPACE/anotherpage.php

The problem is that you cannot read the window.top.location value. You can only write it. Strange but thats it.
Option 1: Mount your app to a page tab and create a like-gate. Like gate will return false outside facebook iframe ALWAYS.
Option 2: Check signed request data when loading the page at backend.
Option 3: Other option is to examinate the top url as you do but at backend.

Related

Facebook apps: Redirect to canvas iframe to URL within app (not main app page)

I'm using the Facebook PHP SDK; setting up an app on Facebook.
I need the app to run within Canvas only, so if the user goes to this url, for example:
http://{site_url}/fbapp/index.php?this=that&that=this&etc=1
I want to:
a) redirect using javascript to the canvas page (ie. http://apps.facebook.com/appname/) and then
b) the iframe must go directly to the page within the app (ie. index.php?this=that&that=this&etc=1)
I've googled this to the moon but not getting anywhere!
Any ideas??
I've tried this:
var currlocation = location.href;
if ( window.self === window.top && !currlocation.match('facebook') ) {
location.href='https://www.facebook.com/dialog/oauth?client_id=<?= $facebook->getAppID() ?>&redirect_uri=<?= $site_url; ?>?<?= $_SERVER['QUERY_STRING']; ?>'; }
It results in an indefinite redirect loop between the site and facebook.
Instead of -
location.href='https://www.facebook.com/dialog/oauth?client_id=getAppID() ?>&redirect_uri=?';
Use-
header("Location: CANVAS_URL");
exit;

How to redirect from Mobile Safari to Native iOS app (like Quora)?

On my iPhone, I just noticed that if I do a Google Search (in Mobile Safari) and select a result on quora.com, the result page launches the native Quora app on my phone.
How is this done? Specifically, is it a detection of the user agent and the use of an iOS URL scheme? Can it tell if the native app is installed and/or redirect to the app store?
I'm reposting an answer to my own related (but was originally Ruby-on-Rails-specific) question from here: Rails: redirect_to 'myapp://' to call iOS app from mobile safari
You can redirect using javascript window.location.
Sample code:
<html><head>
<script type="text/javascript">
var userAgent = window.navigator.userAgent;
if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i)) {
window.location = "myiosapp://"
}
</script>
</head>
<body>
Some html page
</body>
</html>
Just a small improvement of the JS code, if the app is not installed, it will send the user to itunes store ;)
<script type="text/javascript">
// detect if safari mobile
function isMobileSafari() {
return navigator.userAgent.match(/(iPod|iPhone|iPad)/) && navigator.userAgent.match(/AppleWebKit/)
}
//Launch the element in your app if it's already installed on the phone
function LaunchApp(){
window.open("Myapp://TheElementThatIWantToSend","_self");
};
if (isMobileSafari()){
// To avoid the "protocol not supported" alert, fail must open itunes store to dl the app, add a link to your app on the store
var appstorefail = "https://itunes.apple.com/app/Myapp";
var loadedAt = +new Date;
setTimeout(
function(){
if (+new Date - loadedAt < 2000){
window.location = appstorefail;
}
}
,100);
LaunchApp()
}
</script>
You can do trigger your application to be launched using custom URL scheme, registered by your application with the iOS runtime. Then on your website, write code to detect the incoming User-Agent and if iOS is detected generate your custom URL's instead of regular http ones.

Facebook Application: How can I deny direct access on my server?

Is there a way to deny direct access to the application server for a facebook application?
Facebook loads the application via an iFrame src=http://app-domain/, but you can clearly view the page source and find out that domain and copy paste the URL into a browser and view the application directly.
There is this signed_request and oauth_token in the API, I was wondering how to use that or if I can use that to limit direct access to the application.
So if a user inputs in the browser your application's URL he gets redirected to Facebook.
Thank you.
EDIT:
I found a way that also works with form submission.
// Signed request
$signed_request = $facebook->getSignedRequest();
if(!$signed_request) header("Location: " . $settings['appBaseUrl']);
This redirects the browser while accessing the application directly and not through facebook.
It will not work if javascript is disabled.
<script type="text/javascript">
var isInIFrame = (window.location != window.parent.location) ? true : false;
if(!isInIFrame){
window.location = 'link-of-application-page';
}
</script>
You'll need some Javascript to detect whether you're in Facebook's frame and if you're not, redirect to it.
I found a way that also works with form submission. (Works for me, it might not work for you. Test it first.)
// Signed request
$signed_request = $facebook->getSignedRequest();
if(!$signed_request) header("Location: " . $settings['appBaseUrl']);
This redirects the browser while accessing the application directly and not through facebook.

facebook redirect app from canvas page to fan page

im building facebook app as a iframe app in fan page. My problem at the moment is next: i added facebook request dialog (http://developers.facebook.com/docs/reference/dialogs/requests), and everything goes well except for one thing: when a user gets notification, the links goes to canvas page, not to fan page (where i would like to go...)
Since i cant convince facebook to add some funcionality (that would be great), im looking for a way to automaticly redirect from app canvas page to fan page, where this app is added as iframe tab.
I hope somebody understands what i want to do... :)
thanks, Peter
I also wanted to make sure that users view my Facebook app via a Facebook Page Tab (rather than via the Facebook App page or by directly viewing the actual site itself). I have managed to achieve it with this Javascript in a <script> tag in the head of my document (tested Mac/PC FF,Chrome,Opera,IE6-8,Safari).
<script type="text/javascript">
function NotInFacebookFrame() {
return top === self;
}
function ReferrerIsFacebookApp() {
if(document.referrer) {
return document.referrer.indexOf("apps.facebook.com") != -1;
}
return false;
}
if (NotInFacebookFrame() || ReferrerIsFacebookApp()) {
top.location.replace("http://permalink-to-my-facebook-page-tab");
}
</script>
If I understand you correctly, you can do this:
top.location.href='http://www.facebook.com/YOUR_PAGE_NAME?sk=app_YOUR_APP_ID'
or you can use a header to redirect to that url. This will redirect to the application's tab on your fan page.
My application is quite dynamic and I never know which page it's added to. So when I used URL 'http://www.facebook.com/YOUR_PAGE_NAME?sk=app_YOUR_APP_ID' it only redirected me to page, but not to application tab. What I do is:
1) I get page id from signed_request (the encrypted in base64url parameter that your app gets once someone comes to the page, so you have to decrypt it and pick id value from JSON page object)
2) Then I get page data from https://graph.facebook.com/PAGE_ID_YOUR_GET. You get JSON object with some page data in response in JSON format.
3) Only after point 2 I get 'link' value of page from response. It's like http://www.facebook.com/pages/Some-Page-Name
4) And finally I add '?sk=app_YOUR_APP_ID' to page link.
Maybe that's too complicated, but that's the only way it worked for me the way I expected (redirecting exactly to page application tab).
<script type="text/javascript">
function NotInFacebookFrame() {
return top === self;
}
function ReferrerIsFacebookApp() {
if(document.referrer) {
return document.referrer.indexOf("apps.facebook.com") == -1;
}
return false;
}
if (NotInFacebookFrame() || ReferrerIsFacebookApp()) {
top.location.replace("http://permalink-to-my-facebook-page-tab");
}
</script>

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

I'd like to have iOS to open URLs from my domain (e.g. http://martijnthe.nl) with my app whenever the app is installed on the phone, and with Mobile Safari in case it is not.
I read it is possible to create a unique protocol suffix for this and register it in the Info.plist, but Mobile Safari will give an error in case the app is not installed.
What would be a workaround?
One idea:
1) Use http:// URLs that open in any desktop browser and render the service through the browser
2) Check the User-Agent and in case it's Mobile Safari, open a myprotocol:// URL to (attempt) to open the iPhone app and have it open Mobile iTunes to the download of the app in case the attempt fails
Not sure if this will work... suggestions? Thanks!
I think the least intrusive way of doing this is as follows:
Check if the user-agent is that of an iPhone/iPod Touch
Check for an appInstalled cookie
If the cookie exists and is set to true, set window.location to your-uri:// (or do the redirect server side)
If the cookie doesn't exist, open a "Did you know Your Site Name has an iPhone application?" modal with a "Yep, I've already got it", "Nope, but I'd love to try it", and "Leave me alone" button.
The "Yep" button sets the cookie to true and redirects to your-uri://
The "Nope" button redirects to "http://itunes.com/apps/yourappname" which will open the App Store on the device
The "Leave me alone" button sets the cookie to false and closes the modal
The other option I've played with but found a little clunky was to do the following in Javascript:
setTimeout(function() {
window.location = "http://itunes.com/apps/yourappname";
}, 25);
// If "custom-uri://" is registered the app will launch immediately and your
// timer won't fire. If it's not set, you'll get an ugly "Cannot Open Page"
// dialogue prior to the App Store application launching
window.location = "custom-uri://";
It's quite possible to do this in JavaScript as long as your fallback is another applink. Building on Nathan's suggestion:
<html>
<head>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<h2><a id="applink1" href="fb://profile/116201417">open facebook with fallback to appstore</a></h2>
<h2><a id="applink2" href="unknown://nowhere">open unknown with fallback to appstore</a></h2>
<p><i>Only works on iPhone!</i></p>
<script type="text/javascript">
// To avoid the "protocol not supported" alert, fail must open another app.
var appstorefail = "itms://itunes.apple.com/us/app/facebook/id284882215?mt=8&uo=6";
function applink(fail){
return function(){
var clickedAt = +new Date;
// During tests on 3g/3gs this timeout fires immediately if less than 500ms.
setTimeout(function(){
// To avoid failing on return to MobileSafari, ensure freshness!
if (+new Date - clickedAt < 2000){
window.location = fail;
}
}, 500);
};
}
document.getElementById("applink1").onclick = applink(appstorefail);
document.getElementById("applink2").onclick = applink(appstorefail);
</script>
</body>
</html>
Check out a live demo here.
For iOS 6 devices, there is an option: Promoting Apps with Smart App Banners
I found that the selected answer works for the browser apps but I was having issues with the code working in non browser apps that implement a UIWebView.
The problem for me was a user on the Twitter app would click a link that would take them to my site through a UIWebView in the Twitter app. Then when they clicked a button from my site Twitter tries to be fancy and only complete the window.location if the site is reachable. So what happens is a UIAlertView pops up saying are you sure you want to continue and then immediately redirects to the App Store without a second popup.
My solution involves iframes. This avoids the UIAlertView being presented allowing for a simple and elegant user experience.
jQuery
var redirect = function (location) {
$('body').append($('<iframe></iframe>').attr('src', location).css({
width: 1,
height: 1,
position: 'absolute',
top: 0,
left: 0
}));
};
setTimeout(function () {
redirect('http://itunes.apple.com/app/id');
}, 25);
redirect('custom-uri://');
Javascript
var redirect = function (location) {
var iframe = document.createElement('iframe');
iframe.setAttribute('src', location);
iframe.setAttribute('width', '1px');
iframe.setAttribute('height', '1px');
iframe.setAttribute('position', 'absolute');
iframe.setAttribute('top', '0');
iframe.setAttribute('left', '0');
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
};
setTimeout(function () {
redirect('http://itunes.apple.com/app/id');
}, 25);
redirect('custom-uri://');
EDIT:
Add position absolute to the iframe so when inserted there isn't a random bit of whitespace at the bottom of the page.
Also it's important to note that I have not found a need for this approach with Android. Using window.location.href should work fine.
In iOS9 Apple finally introduced the possibility to register your app to handle certain http:// URLs: Universal Links.
A very rough explanation of how it works:
You declare interest in opening http:// URLs for certain domains (web urls) in your app.
On the server of the specified domains you have to indicate which URLs to open in which app that has declared interest in opening URLs from the server's domain.
The iOS URL loading service checks all attempts to open http:// URLs for a setup as explained above and opens the correct app automatically if installed; without going through Safari first...
This is the cleanest way to do deep linking on iOS, unfortunately it works only in iOS9 and newer...
BUILDING Again on Nathan and JB's Answer:
How To Launch App From url w/o Extra Click
If you prefer a solution that does not include the interim step of clicking a link, the following can be used. With this javascript, I was able to return a Httpresponse object from Django/Python that successfully launches an app if it is installed or alternatively launches the app store in the case of a time out. Note I also needed to adjust the timeout period from 500 to 100 in order for this to work on an iPhone 4S. Test and tweak to get it right for your situation.
<html>
<head>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<script type="text/javascript">
// To avoid the "protocol not supported" alert, fail must open another app.
var appstorefail = "itms://itunes.apple.com/us/app/facebook/id284882215?mt=8&uo=6";
var loadedAt = +new Date;
setTimeout(
function(){
if (+new Date - loadedAt < 2000){
window.location = appstorefail;
}
}
,100);
function LaunchApp(){
window.open("unknown://nowhere","_self");
};
LaunchApp()
</script>
</body>
</html>
window.location = appurl;// fb://method/call..
!window.document.webkitHidden && setTimeout(function () {
setTimeout(function () {
window.location = weburl; // http://itunes.apple.com/..
}, 100);
}, 600);
document.webkitHidden is to detect if your app is already invoked and current safari tab to going to the background, this code is from www.baidu.com
If you add an iframe on your web page with the src set to custom scheme for your App, iOS will automatically redirect to that location in the App. If the app is not installed, nothing will happen. This allows you to deep link into the App if it is installed, or redirect to the App Store if it is not installed.
For example, if you have the twitter app installed, and navigate to a webpage containing the following markup, you would be immediately directed to the app.
<!DOCTYPE html>
<html>
<head>
<title>iOS Automatic Deep Linking</title>
</head>
<body>
<iframe src="twitter://" width="0" height="0"></iframe>
<p>Website content.</p>
</body>
</html>
Here is a more thorough example that redirects to the App store if the App is not installed:
<!DOCTYPE html>
<html>
<head>
<title>iOS Automatic Deep Linking</title>
<script src='//code.jquery.com/jquery-1.11.2.min.js'></script>
<script src='//mobileesp.googlecode.com/svn/JavaScript/mdetect.js'></script>
<script>
(function ($, MobileEsp) {
// On document ready, redirect to the App on the App store.
$(function () {
if (typeof MobileEsp.DetectIos !== 'undefined' && MobileEsp.DetectIos()) {
// Add an iframe to twitter://, and then an iframe for the app store
// link. If the first fails to redirect to the Twitter app, the
// second will redirect to the app on the App Store. We use jQuery
// to add this after the document is fully loaded, so if the user
// comes back to the browser, they see the content they expect.
$('body').append('<iframe class="twitter-detect" src="twitter://" />')
.append('<iframe class="twitter-detect" src="itms-apps://itunes.com/apps/twitter" />');
}
});
})(jQuery, MobileEsp);
</script>
<style type="text/css">
.twitter-detect {
display: none;
}
</style>
</head>
<body>
<p>Website content.</p>
</body>
</html>
Heres a solution.
Setup a boolean sitiation using blur and focus
//see if our window is active
window.isActive = true;
$(window).focus(function() { this.isActive = true; });
$(window).blur(function() { this.isActive = false; });
Bind your link with a jquery click handler that calls something like this.
function startMyApp(){
document.location = 'fb://';
setTimeout( function(){
if (window.isActive) {
document.location = 'http://facebook.com';
}
}, 1000);
}
if the app opens, we'll lose focus on the window and the timer ends. otherwise we get nothing and we load the usual facebook url.
You can't, as far as I know, make the entire OS understand an http:+domain URL. You can only register new schemes (I use x-darkslide: in my app). If the app is installed, Mobile Safari will launch the app correctly.
However, you would have to handle the case where the app isn't installed with a "Still here? Click this link to download the app from iTunes." in your web page.
Check the User-Agent and in case it's
Mobile Safari, open a myprotocol://
URL to (attempt) to open the iPhone
app and have it open Mobile iTunes to
the download of the app in case the
attempt fails
This sounds a reasonable approach to me, but I don't think you'll be able to get it to open mobile itunes as a second resort. I think you'll have to pick one or the other - either redirect to your app or to itunes.
i.e. if you redirect to myprotocol://, and the app isn't on the phone, you won't get a second chance to redirect to itunes.
You could perhaps first redirect to an (iphone optimised) landing page and give the user the option to click through to your app, or to itunes to get the app if they don't have it? But, you'll be relying on the user to do the right thing there. (Edit: though you could set a cookie so that is a first-time thing only?)
In seeking to fix the problem of pop-up, I discovered that Apple had a way around this concern.
Indeed, when you click on this link, if you installed the application, it is rerouted to it; otherwise, you will be redirected to the webpage, without any pop-up.
It also possible to check tab activity by document.hidden property
Possible solution
document.location = 'app://deep-link';
setInterval( function(){
if (!document.hidden) {
document.location = 'https://app.store.link';
}
}, 1000);
But seems like this not works in Safari