Simple mobile redirect / deep link implementation - javascript

So I have a redirect working, but it's a little janky & I'm hoping to make it less janky :)
I'm using deep linking to basically open the app only....nothing beyond that at the moment.
Below is the redirect for ios. It works ok, but it's throwing a URL error in safari that I have to tap to close before it will redirect to the app store. (This is the case of a user not having the app installed)
So...I know universal linking is what iOS9 is doing, but I'm trying to avoid implementing too much on the native code side. All I've done is add my custom URL scheme to the plist of the app.
So wise internet...is there a better way?
else if(isMobile.iOS())
{
window.onload = function() {
window.location = 'vrbhome://';
setTimeout("window.location = 'https://itunes.apple.com/us/app/vrb/id1066438072?ls=1&mt=8';", 1000);
}
}
else {
document.location.href="http://vrb.is";
}

This error is by (Apple's) design — the only way to work around it is to decrease the timeout enough that the user goes to the App Store before they have a chance to see the error. Unfortunately as of iOS 9.2, users with your app will also be redirected before they have a chance open the app. Universal Links are the solution Apple wishes you to use.
If you don't want to handle too much native code, you could try https://branch.io

Related

How to hide JScripts in Developers tools? [duplicate]

I'm developing a web application and since it has access to a database underneath, I require the ability to disable the developer tools from Safari, Chrome, Firefox and Internet Explorer and Firebug in Firefox and all similar applications. Is there a way to do this?
Note: The AJAX framework provided by the database requires that anything given to the database to be in web parameters that can be modified and that anything it returns be handled in JavaScript. Therefore when it returns a value like whether or not a user has access to a certain part of the website, it has to be handled in JavaScript, which developer tools can then access anyway. So this is required.
UPDATE: For those of you still thinking I'm making bad assumptions, I did ask the vendor. Below is their response:
Here are some suggestions for ways of mitigating the risk:
1) Use a javascript Obfuscator to obfuscate the code and only provide
the obfuscated version with the sold application; keep the non
obfuscated version for yourself to do edits. Here is an online
obfuscator:
How can I obfuscate (protect) JavaScript?
http://en.wikipedia.org/wiki/Obfuscated_code
http://javascriptobfuscator.com/default.aspx
2) Use a less descriptive name; maybe 'repeatedtasks.js' instead of
'security.js' as 'security.js' will probably stand out more to anyone
looking through this type of information as something important.
No you cannot do this.
The developer menu is on the client side and is provided by the user's browser.
Also the browser developer should have nothing to do with your server side database code, and if it does, you need some maaaaaajor restructuring.
If your framework requires that you do authorization in the client, then...
You need to change your framework
When you put an application in the wild, where users that you don't trust can access it; you must draw a line in the sand.
Physical hardware that you own; and can lock behind a strong door. You can do anything you like here; this is a great place to keep your database, and to perform the authorization functions to decide who can do what with your database.
Everything else; Including browsers on client computers; mobile phones; Convenience Kiosks located in the lobby of your office. You cannot trust these! Ever! There's nothing you can do that means you can be totally sure that these machines aren't lying to cheat you and your customers out of money. You don't control it, so you can't ever hope to know what's going on.
In fact this is somehow possible (how-does-facebook-disable-developer-tools), but this is terribly bad idea for protecting your data. Attacker may always use some other (open, self written) engines that you don't have any control on. Even javascript obfuscation may only slow down a bit cracking of your app, but it also gives practically no security.
The only reasonable way to protect your data is to write secure code on server side.
And remember, that if you allow someone to download some data, he can do with it whatever he wants.
There's no way your development environment is this brain-dead. It just can't be.
I strongly recommend emailing your boss with:
A demand for a week or two in the schedule for training / learning.
A demand for enough support tickets with your vendor to figure out how to perform server-side validation.
A clear warning that if the tool cannot do server-side validation, that you will be made fun of on the front page of the Wall Street Journal when your entire database is leaked / destroyed / etc.
No. It is not possible to disable the Developer Tools for your end users.
If your application is insecure if the user has access to developer tools, then it is just plain insecure.
Don't forget about tools like Fiddler. Where even if you lock down all the browsers' consoles, http requests can be modified on client, even if you go HTTPS. Fiddler can capture requests from browser, user can modify it and re-play with malicious input. Unless you secure your AJAX requests, but I'm not aware of a method how to do this.
Just don't trust any input you receive from any browser.
you cannot disable the developer tool. but you can annoys any one who try to use the developer tool on your site, try the javascript codes blow, the codes will break all the time.
(function () {
(function a() {
try {
(function b(i) {
if (('' + (i / i)).length !== 1 || i % 20 === 0) {
(function () { }).constructor('debugger')()
} else {
debugger
}
b(++i)
}
)(0)
} catch (e) {
setTimeout(a, 5000)
}
}
)()
}
)();
Update at the time (2015) when this answer was posted, this trick was possible. Now (2017) browsers are mature. Following trick no longer works!
Yes it is possible. Chrome wraps all console code in
with ((console && console._commandLineAPI) || {}) {
<code goes here>
}
... so the site redefines console._commandLineAPI to throw:
Object.defineProperty(console, '_commandLineAPI',
{ get : function() { throw 'Nooo!' } })
This is the main trick!
$('body').keydown(function(e) {
if(e.which==123){
e.preventDefault();
}
if(e.ctrlKey && e.shiftKey && e.which == 73){
e.preventDefault();
}
if(e.ctrlKey && e.shiftKey && e.which == 75){
e.preventDefault();
}
if(e.ctrlKey && e.shiftKey && e.which == 67){
e.preventDefault();
}
if(e.ctrlKey && e.shiftKey && e.which == 74){
e.preventDefault();
}
});
!function() {
function detectDevTool(allow) {
if(isNaN(+allow)) allow = 100;
var start = +new Date();
debugger;
var end = +new Date();
if(isNaN(start) || isNaN(end) || end - start > allow) {
console.log('DEVTOOLS detected '+allow);
}
}
if(window.attachEvent) {
if (document.readyState === "complete" || document.readyState === "interactive") {
detectDevTool();
window.attachEvent('onresize', detectDevTool);
window.attachEvent('onmousemove', detectDevTool);
window.attachEvent('onfocus', detectDevTool);
window.attachEvent('onblur', detectDevTool);
} else {
setTimeout(argument.callee, 0);
}
} else {
window.addEventListener('load', detectDevTool);
window.addEventListener('resize', detectDevTool);
window.addEventListener('mousemove', detectDevTool);
window.addEventListener('focus', detectDevTool);
window.addEventListener('blur', detectDevTool);
}
}();
https://github.com/theajack/disable-devtool
This tool just disabled devtools by detecting if its open and then just closing window ! Very nice alternative. Cudos to creator.
I found a way, you can use debugger keyword to stop page works when users open dev tools
(function(){
debugger
}())
Yeah, this is a horrible design and you can't disable developer tools. Your client side UI should be sitting on top of a rest api that's designed in such a way that a user can't modify anything that was already valid input anyways.
You need server side validation on inputs. Server side validation doesn't have to be verbose and rich, just complete.
So for example, client side you might have a ui to show required fields etc. But server side you can just have one boolean set to true, and set it to false if a field fails validation and then reject the whole request.
Additionally your client side app should be authenticated. You can do that 100 thousand ways. But one I like to do is use ADFS passthrough authentication. They log into the site via adfs which generates them a session cookie. That session cookie get's passed to the rest api (all on the same domain) and we authenticate requests to the rest api via that session cookie. That way, no one that hasn't logged in via the login window can call the rest api. It can only be called form their browser context.
Developer tool wise, you need to design your app in such a way that anything that a user can do in the developer console is just a (feature) or a breaking thing. I.e. say they fill out all the fields with a js snippet, doesn't matter, that's valid input. Say they override the script and try to send bad data to the api calls. Doesn't matter, your server side validation will reject any bad input.
So basically, design your app in such a way that developer tool muckery either brakes their experience (as it won't work), or lets them make their lives a little easier, like auto selecting their country every time.
Additionally, you're not even considering extensions... Extensions can do anything and everything the developer console can do....
I am just throwing a random Idea maybe this will help.
If someone tries to open the developer tool just redirect to some other site.
I don't know how much this is gonna effective for you but at least they can't perform something on your site.
You can not block developer tools, but you can try to stop the user to enter them. You can try to customize a right-click menu and block the keystrokes for developer tools.
You can't disable developer tools
However...
I saw one website uses a simple trick to make devtools unusable. It worked like this - when the user opens devtools the whole page turns into blank page, and the debugger in devtools is stuck in a loop on a breakpoint. Even page refresh doesn't get you out of that state.
Yes. No one can control client browser or disable developer tool or debugger tool.
But you can build desktop application with electron.js where you can launch your website. Where you can stop debugger or developer tool.
Our team snippetbucket.com had build plenty of solution with electron.js, where similar requirement was their. as well restructure and protect website with many tools.
As well with electron.js many web solution converted and protected in well manner.
You can easily disable Developer tools by defining this:
Object.defineProperty(console, '_commandLineAPI', { get : function() { throw 'Nooo!' } })
Have found it here: How does Facebook disable the browser's integrated Developer Tools?

Using branch.io to redirect to app in javascript

So, we have a mobile download site that we want to bypass if the user already has our app installed, and open our app. We are using the branch javascript code to try to accomplish this task. We have our branch key where I have 'my_branch_key', and we copied the rest of the code below directly out of the branch instructions. And, of course, it is failing to redirect our mobile users. I imagine the problem is the lack of some sort of app identifier in the code, but we could not find any instructions on where to add that. Anyone know what we're missing and where we need to add it. Any advice would be greatly appreciated.
// load the Branch SDK file
(function(b,r,a,n,c,h,_,s,d,k){if(!b[n]||!b[n]._q){for(;s<_.length;)c(h,_[s++]);d=r.createElement(a);d.async=1;d.src="https://cdn.branch.io/branch-latest.min.js";k=r.getElementsByTagName(a)[0];k.parentNode.insertBefore(d,k);b[n]=h}})(window,document,"script","branch",function(b,r){b[r]=function(){b._q.push([r,arguments])}},{_q:[],_v:1},"addListener applyCode banner closeBanner creditHistory credits data deepview deepviewCta first getCode init link logout redeem referrals removeListener sendSMS setIdentity track validateCode".split(" "), 0);
branch.init('my_branch_key');
// define the deepview structure
branch.deepview(
{
'channel': 'mobile_web',
'feature': 'deepview',
data : {
'source': 'website'
}
},
{
'open_app': true
}
);
Additional info: We noticed an oddity when trying to test this, for a couple of our iPhone users, it seems to work perfectly, but for the rest of the iPhone users and all the android users it still fails to redirect.
Alex with Branch.io here: the automatic open_app: true setting actually doesn't work in iOS 9 with Safari, due to some changes Apple made to Universal Links in iOS 9.3. This is a fairly recent change, so our docs haven't been updated quite yet. It's annoying, I agree...
The best workaround is to put a button on the page with deepviewCta(). Visitors will have to click it to open the app. We realise this is not ideal, but it's the best option for Apple's current system.
The other option you can try is enabling your own domain for Universal Link. That way whenever a URL at your domain is clicked, your app will launch immediately and the site will never even be loaded.

HashNavigation in cordova wp8 hangs app

I have next code
function navigate(_hash){
alert('before');
//try#1
window.location.hash = _hash;
//try#2
// window.location.href=window.location.href.split("#")[0]+"#" +url;
alert('after');
}
navigate('someurl')
the issue is that after changing url hash (both variants) app just hangs. And interesting thing that second alert is not firing. so app just... crashes after some time.
Nothing in js console.
Debug log says
The thread 0x*** has exited with code 259 (0x103).
google found nothing on that. Seems like this is acommon error code.
More details:
i'm using ChaplinJs so just can't get away from hash navigation.
second thought was that chaplin overloads system and we caanot get anywhere, but(!) putting logs and alerts in source of lib in window.on('hashchange',....) also didn't make any effort because we do not get there also.
WP 8.0
tried both Cordova 4.* and 5.*
also tried to modify xhrXelper.cs but it is not related tonavigation itself.
PS: I know that jquery mobile suggests to disable hashchanges onmobile navigation. But i can't :(
PPS: also tried todisable chaplin haschanges
new App({routes: routes, controllerSuffix: '-controller', pushState: false,hashChange:true})
but this also didn't make any good results because it's placing hash to href to check it in interval and app hanged again. So i assume that is a webview problem
More additional info:
continious re-run of app makes it work sometimes (1 run of 10 can make it work). That's very strange.
Emulator and device behave in the same way.
Update: Read somewhere that it's critical to restrict navigting before "deviceready" event.
But this is also not a case.
Update2: create cordova proj from scratch. Added hash change indeviceready cb and it hangs
Update3: same code on 8.1 works perfect

Launch app from link, if no app then go to download app from web

So I'm looking to launch a mobile app when a web page is landed on. I've seen this done and all is great there (see code below with Facebook and Pandora as an example). But I'm looking for a logic check to route the user one way or the other depending upon the successful or unsuccessful launch of the app. It was said in a previous solution that you cannot use a link to check the user's mobile device to see if an app is installed, but I keep thinking that there might be a way to see if the user's app was successfully launched after-the-fact and route them based on that.
Using the code below, if the app is launched, the web page falls away, if you will (disappears into the background while the app takes center stage). If, however, the app isn't installed on the mobile device, then the web page stays up and you get an error (can't recall off-hand which error). But it seems to me that receipt of this error should be able to trigger a re-routing to a specific URL of your choice. Not at the server-level, but at the code-level. In other words... if the app launches, then grats... enjoy! But if the page loads with an error, then it redirects instantly to say, the app download page on Apple or Google (depending upon the OS detected).
Does anyone have a suggestion as to how to make this happen? Essentially one piece of code that is looking for the trigger error and reacting to that as a way to A) launch the app from a page load (link) B) open the app store in a browser to download the app if the app wasn't successfully launched.
This is my first foray into Stack, but I have found the community very helpful over the years.
<script type="text/javascript"> // <![CDATA[
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
if ( isMobile.Android() ) {
document.location.href = "fb://profile";
}
else if(isMobile.iOS())
{
document.location.href="pandora://";
}
</script>
What you're talking about is called Deferred Deep Linking in terms of App Links. If you were coding an app that wanted to utilize this, there are iOS guides and Android ones. Overall, there doesn't seem to be a standard implementation for all scenarios, however, there is a pretty simple "roll-your-own" implementation that is similar to what you're attempting.
(from another SO answer)
<script type="text/javascript">
window.onload = function() {
// Deep link to your app goes here
document.getElementById("l").src = "my_app://";
setTimeout(function() {
// Link to the App Store should go here -- only fires if deep link fails
window.location = "https://itunes.apple.com/us/app/my.app/id123456789?ls=1&mt=8";
}, 500);
};
</script>
<iframe id="l" width="1" height="1" style="visibility:hidden"></iframe>
As a commentor said above, use an iframe so you can keep processing code even if your window.location fails. Then, set up a simple setTimeout with a reasonable fallback time. You don't need to catch any error messages or response headers. If the app didn't launch, then a website will.
Just thought to add, since you want A) Launch App from link and upon failure B) Go to store to download the app.
A Cross-Platform solution you can use rather than rolling your own as an alternative, I'd suggest trying Firebase Dynamic Links (works on both Android and iOS) and its free.
It also has the benefit of providing your app the link information, like if you put in the link an article ID (from your news website example), then the app can load up that article upon launch, and it persists even if the user has to install the app from the store, when launched it will open to that article you specified in the link.
In addition, Dynamic Links work across app installs: if a user opens a Dynamic Link on iOS or Android and doesn't have your app installed, the user can be prompted to install it; then, after installation, your app starts and can access the link.
https://firebase.google.com/docs/dynamic-links
With very little code you can add the ability for a user to click a link on your mobile web and be taken to the corresponding page in your app, even if they have to go to the App Store or Google Play Store to install it first!
https://firebase.google.com/docs/dynamic-links/use-cases/web-to-app

Deeplinking mobile browsers to native app - Issues with Chrome when app isn't installed

I have a webpage, lets call it entry.html.
When a user enters this page, a javascript code (see below) is attempting to deep-link the user to the native iOS / Android app.
If the deep-link fails (probably if the app isn't installed on device), user should "fall back" to another page- lets call it fallback.html.
here is the javascript code that is running on entry.html:
$(function(){
window.location = 'myapp://';
setTimeout(function(){
window.location = 'fallback.html';
}, 500);
});
this is a standard deep-linking method that is recommended all over the network; try to deep-link, and if the timeout fires it means that deep-link didn't occur- so fallback.
this works fine, as long app is installed on device.
but if the app isn't installed, this is the behaviour when trying to deep-link:
Mobile Safari: I see an alert message saying "Safari cannot open this page..." for a moment, and then it falls-back properly to fallback.html- which is the expected behaviour.
Mobile Chrome is my problem.
when the app isn't installed, browser is actually redirected to the myapp:// url, which is of course, invalid- so i get a "not found" page, and fall-back doesn't occur.
Finally- my question is:
How can I fix my code so FALL-BACK WILL OCCUR on mobile Chrome as well? just like mobile Safari?
note: i see that LinkedIn mobile website does this properly, with Safari & Chrome, with or without the app installed, but i couldn't trace the code responsible for it :(
note2: i tried appending an iframe instead of window.location = url, this works only on Safari, mobile Chrome doesn't deep-link when appending an iFrame even if app is installed.
Thanks all!
UPDATE:
i found a decent solution, and answered my own question. see accepted answer for my solution.
for whoever is interested, i managed to find a decent solution to solve these issues with deeplinking Chrome on Android.
i abandoned the myapp:// approach, i left it functioning only in cases of an iOS device.
for Android devices, i'm now using intents which are conceptually different than the myapp:// protocol.
I'm mainly a web developer, not an Android developer, so it took me some time to understand the concept, but it's quite simple. i'll try to explain and demonstrate MY solution here (note that there are other approaches that could be implemented with intents, but this one worked for me perfectly).
here is the relevant part in the Android app manifest, registering the intent rules (note the android:scheme="http" - we'll talk about it shortly):
<receiver android:name=".DeepLinkReceiver">
<intent-filter >
<data android:scheme="http" android:host="www.myapp.com" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
now, after this is declared in the app manifest, i'm sending myself an email with "http://www.myapp.com" in the message.
when link is tapped with the Android device, a "chooser" dialog comes up, asking with which application i want to open the following? [chrome, myapp]
the reason this dialog came up upon tapping on a "regular" url, is because we registered the intent with the http scheme.
with this approach, the deeplink isn't even handled in the webpage, it's handled by the device itself, when tapping a matching link to an existing intent rule defined in the Android app manifest.
and yes, as i said, this approach is different by concept than the iOS approach, which invokes the deeplink from within the webpage, but it solves the problem, and it does the magic.
Note: when app isn't installed, no chooser dialog will come up, you'll just get navigated to the actual web page with the given address (unless you have more than 1 browser, so you'll need to choose one... but lets not be petty).
i really hope that this could help someone who's facing the same thing.. wish i had such an explanation ;-)
cheers.
It is very important to make sure that when you try to open a deeplink URL with JavaScript that the URL is properly formatted for the device and browser. (If you do not use the appropriate deeplink URL for the browser/platform, a user may be redirected to a “Page Not Found”, which is what you experience.)
Now you must note that Chrome on Android has a different URL format than the old standard Android browser 1! You need to annotate the deep links using href="android-app://" in the HTML markup of your web pages. You can do this in the section for each web page by adding a tag and specifying the deep link as an alternate URI.
For example, the following HTML snippet shows how you might specify the corresponding deep link in a web page that has the URL example://gizmos.
<html>
<head>
<link rel="alternate"
href="android-app://com.example.android/example/gizmos" />
...
</head>
<body> ... </body>
For more details, see the references here:
https://developer.chrome.com/multidevice/android/intents
https://developers.google.com/app-indexing/webmasters/server
https://developer.android.com/training/app-indexing/enabling-app-indexing.html#webpages
And here's a deep link testing tool for Android: https://developers.google.com/app-indexing/webmasters/test.html
Hope that helps.
1 Since the old AOSP browser was replaced by chromium, this is now the default way to handle deep links for recent Android versions. Nonetheless, Android still requires a conditional soltion, because older OS versions still use the AOSP browser.
I have created a Javascript plugin, which supports most of the modern browsers on mobile. But it requires to have deep linking landing pages to be hosted on cross domain(different than universal link url) to work on ios9 Facebook using universal linking. There is also different way to get that working on the Facebook iOS9 using Facebook SDK. I am sharing this if anyone might find this helpful. Currently it does not fallback option, but if falls back to the App Store.
https://github.com/prabeengiri/DeepLinkingToNativeApp
I am Using this Code to for deeplinking.
If the app is installed the app will open up..
If the app is not installed then this remains as it is..
If you wish to add any other condition for app no install then just uncomment the setTimeout code .
<script>
var deeplinking_url = scootsy://vendor/1;
$(document).ready(function(){
call_me_new(deeplinking_url);
});
var call_me_new = function(deeplinking_url){
if(deeplinking_url!=''){
var fallbackUrl ='http://scootsy.com/';
var iframe = document.createElement("iframe");
var nativeSchemaUrl = deeplinking_url;
console.log(nativeSchemaUrl);
iframe.id = "app_call_frame";
iframe.style.border = "none";
iframe.style.width = "1px";
iframe.style.height = "1px";
iframe.onload = function () {
document.location = nativeSchemaUrl;
};
iframe.src = nativeSchemaUrl; //iOS app schema url
window.onload = function(){
document.body.appendChild(iframe);
}
//IF the App is not install then it will remain on the same page.If you wish to send the use to other page then uncomment the below code and send a time interval for the redirect.
/*
setTimeout(function(){
console.log('Iframe Removed...');
document.getElementById("app_call_frame").remove();
window.location = fallbackUrl; //fallback url
},5000);*/
}
};
</script>
setTimeout(function () { if (document.hasFocus()) { window.location = 'URL WILL BEHERE';} }, 2000);
window.location = 'app://';
Need to check document.hasFocus() here because if app is open then playstore url is also open in browser
I also had similar issue, there is a possible alternative for this. If the app is not installed on user's device we can redirect that to some other url.To know more about it Check Here
Example:
Take a QR code
In my case its working fine in opera and chrome browser my deeplink url is
"intent://contentUrl + #Intent;scheme=" +envHost +;package="+envHost+";end";
For other browser create iframe and append the url.
Note -: iframe url append having issue with old device and in firefox its opening app dialog .

Categories