How to open Twitter and Facebook app with Phonegap? - javascript

I am trying to have my PhoneGap application link to open a specific users profile page in the Twitter app. I know not everyone has the Twitter app installed on their device so I wanted to send them to the Play Store to download it if they didn't.
Problem is that every time I tap the link on my Android device I receive an error:
Application Error:
net::ERR_UNKNOWN_URL_SCHEME(twitter://user?screen_name=xerxesnoble)
My JavaScript is as follows:
//If Android
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if (isAndroid) {
alert('Android!');
twitterCheck = function() {
alert('Android!');
var now = new Date().valueOf();
setTimeout(function () {
if (new Date().valueOf() - now > 100) return;
window.open('https://play.google.com/store/apps/details?id=com.twitter.android', '_system', 'location=no');
}, 50);
window.open('twitter://user?screen_name=XerxesNoble', '_system', 'location=no');
};
};
$('.twiterNav').click(function() {
window.open('twitter://user?screen_name=xerxesnoble', '_system', 'location=no');
});
Things that I've tried:
Using twitter:/// instead of twitter://
Adding <access origin="twitter://user?screen_name=xerxesnoble" /> to my config.xml
I'm not sure what else to try, nothing is working for Facebook either but right now I'm focusing on one issue at a time.

The Problem is that the InAppBrowser plugin was not installed. New versions of PhoneGap/Cordova do not come with all plugins installed- instead you choose what you want your App to have access to.
In terminal cd yourApp and $ cordova plugin add org.apache.cordova.inappbrowser
After doing that, it worked perfectly.
EDIT
Just to branch out a little bit more on how I got my .js to check if twitter was installed or not.
I installed another plugin : AppAvailability for iOS and Android
Then I altered my .js to look like this:
//Twitter checker
// If Mac//
var twitterCheck = function(){
appAvailability.check('twitter://', function(availability) {
// availability is either true or false
if(availability) { window.open('twitter://user?screen_name=xerxesnoble', '_system', 'location=no');}
else{window.open('https://itunes.apple.com/ca/app/twitter/id333903271?mt=8', '_system', 'location=no'); };
});
};
//If Android
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if(isAndroid) {
twitterCheck = function(){
appAvailability.check('com.twitter.android', function(availability) {
// availability is either true or false
if(availability) {window.open('twitter://user?screen_name=xerxesnoble', '_system', 'location=no');}
else{window.open('https://play.google.com/store/apps/details?id=com.twitter.android', '_system', 'location=no');};
});
};
};
The documentation provided in the AppAvailability plugin was very helpful as well>
Hope that this helps someone!

Just a reference for others who might come here and want a bit more:
I've been able to get this working well (so far) on both iOS and Android, and dynamically falling back to the browser using the code below.
Required plugins are cordova-plugin-inappbrowser and cordova-plugin-appavailability
function openBrowser (url) {
if (!url) {
return;
}
// turn my url into a scheme/intent url
getAvailabilityScheme(url, function (url) {
window.open(url, '_system');
});
}
function getAvailabilityScheme (url, callback) {
var schemeOrPackage;
var schemeUrl;
// check for appavaialbility plugin
if (!window.appAvailability) {
callback(url);
}
// facebook
if (url.indexOf('facebook.com/') !== -1) {
schemeOrPackage = isAndroid ? 'com.facebook.katana' : 'fb://'
schemeUrl = 'fb://profile/' + url.split('facebook.com/')[1];
}
// twitter
if (url.indexOf('twitter.com/') !== -1) {
schemeOrPackage = isAndroid ? null : 'twitter://'
schemeUrl = 'twitter://user?screen_name=' + url.split('twitter.com/')[1];
}
if (schemeOrPackage && schemeUrl) {
window.appAvailability.check(schemeOrPackage, function () {
callback(schemeUrl);
}, function () {
callback(url);
});
} else {
callback(url);
}
}
Using it is easy, just call the openBrowser(url) method with a normal website url. The only issue i found was that for a facebook page, it needs to an ID not the slug name

Related

Redirect mobile users to app or store if not installed

I'd like to have iOS/Android to open URLs from my domain (e.g. http://somedomain.com) with my app whenever the app is installed on the phone, or to go to app/play store links to the app if not.
I read it is possible to create a unique protocol suffix for this so I assume a JavaScript can do the job?
What could be the right approach for this?
Tried this but didn't work:
How to redirect the user to a mobile app or a website on click of a hyperlink sent in an email? Should it need to be handled on server-side using PHP?
<script>
/*$(document).ready(function () {
console.log('Redirect to APP');
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
// Windows Phone must come first because its UA also contains "Android"
if (/windows phone/i.test(userAgent)) {
//return "Windows Phone";
console.log('Windows Phone');
}
if (/android/i.test(userAgent)) {
//return "Android";
console.log('Android');
var now = new Date().valueOf();
setTimeout(function () {
if (new Date().valueOf() - now > 100) return;
window.location = "https://play.google.com/store/apps/";
}, 25);
window.location = "appname://";
}
if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
//return "iOS";
console.log('iOS');
var now = new Date().valueOf();
setTimeout(function () {
if (new Date().valueOf() - now > 100) return;
window.location = "https://itunes.apple.com/appdir";
}, 25);
window.location = "appname://";
}
});*/
</script>

How to add back button event in Universal Windows App without using WinjS Library?

This is my main.js
(function () {
"use strict";
//No need of WinJS
var activation = Windows.ApplicationModel.Activation;
var roaming = Windows.Storage.ApplicationData.current.roamingSettings;
// For App Start Up
Windows.UI.WebUI.WebUIApplication.addEventListener("activated", function (args) {
if (args.detail[0].kind === activation.ActivationKind.launch) {
if (roaming.values["currentUri"]) {
if (roaming.values["UserName"])
{
localStorage.setItem("UserName", roaming.values["UserName"]);
window.location.href = roaming.values["currentUri"];
}
}
}
});
// For App Suspension
Windows.UI.WebUI.WebUIApplication.addEventListener("suspending", function (args) {
roaming.values["currentUri"] = window.location.href;
roaming.values["UserName"] = localStorage.getItem("UserName");
});
// For Resuming App
Windows.UI.WebUI.WebUIApplication.addEventListener("resuming", function (args) {
var roam = Windows.Storage.ApplicationData.current.roamingSettings;
if (roam) {
if (roam.values["currentUri"]) {
localStorage.setItem("UserName", roam.values["UserName"]);
window.location.href = roam.values["currentUri"];
}
}
}, false);
// not working backpressed event
Windows.UI.WebUI.WebUIApplication.addEventListener("backpressed", function (args) {
// to do
}, false);})();
I need to add back key press event for windows phone without using winjs library?
Can anyone suggest me?
I am using ms-appx-web context in my app. I dont want to use winjs library.
I need to add back key press event for windows phone without using winjs library?
The backpressed event should be attached to Windows.Phone.UI.Input.HardwareButtons but not Windows.UI.WebUI.WebUIApplication.
If you refer to HardwareButtons.BackPressed and HardwareButtons, you will find the backpressed event is used like this:
var hardwareButtons = Windows.Phone.UI.Input.HardwareButtons;
function onBackPressed(eventArgs) { /* Your code */ }
// addEventListener syntax
hardwareButtons.addEventListener("backpressed", onBackPressed);
hardwareButtons.removeEventListener("backpressed", onBackPressed);
And since you are not making a Single Page Application. This event should be attached on every new page's JS codes.
Update: If you want to know your current device programmatically, you can use the following if-statement:
if (deviceInfo.operatingSystem.toLowerCase() == "windowsphone")
{
//do your windows phone logic
} else if (deviceInfo.operatingSystem.toLowerCase() == "windows")
{
//do your windows logic
}
I used this-
var flag = Windows.Foundation.Metadata.ApiInformation.isTypePresent("Windows.Phone.UI.Input.HardwareButtons");
if (flag) {
var hardwareButtons = Windows.Phone.UI.Input.HardwareButtons;
hardwareButtons.addEventListener("backpressed", onBackPressed);
}
It worked for me well!

Windows 10 universal app not resuming from previous session

I have developed a windows 10 universal app using Html,css and JS. For allowing inline scripts i am using ms-appx-web context and has set ms-appx-web:///login.html as start page in manifest.
Whenever I open my app in windows 10 mobile it works fine but if I switch to another app and then go to app again by selecting it from windows app list. Then it instead of resuming app from saved state it restarts it.
(function () {
"use strict";
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState === activation.ApplicationExecutionState.terminated) {
}
if (WinJS.Application.sessionState.url) {
localStorage.setItem("UserName", WinJS.Application.sessionState.name);
window.location = WinJS.Application.sessionState.url;
}
args.setPromise(WinJS.UI.processAll().then(function () {
}));
}
};
app.oncheckpoint = function (args) {
var location = window.location.href;
var name = localStorage.getItem("UserName");
WinJS.Application.sessionState.name = name;
WinJS.Application.sessionState.url = location;
};
Windows.UI.WebUI.WebUIApplication.addEventListener("resuming", function (args) {
if (WinJS.Application.sessionState) {
window.location = WinJS.Application.sessionState.url;
localStorage.setItem("UserName", WinJS.Application.sessionState.name);
}
}, false);
Windows.UI.WebUI.WebUIApplication.addEventListener("suspending", function (args) {
var location = window.location.href;
var name = localStorage.getItem("UserName");
WinJS.Application.sessionState.name = name;
WinJS.Application.sessionState.url = location;
}, false);
app.start();
})();
Can anyone suggest me what am I doing wrong?
I changed my app.onactivated event in main.js
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
} else {
}
args.setPromise(WinJS.UI.processAll());
var name = Windows.Storage.ApplicationData.current.roamingSettings.values["name"];
var url = Windows.Storage.ApplicationData.current.roamingSettings.values["url"];
if (name) {
localStorage.setItem("UserName", name);
}
if (url) {
window.location.href = url;
}
}
};
But it stops running on window.location.href = url; line.
What i am trying to do is store username and current url on suspending event and want to restore it on resume event (when user opens app from app list which is already running.)
but if I switch to another app and then go to app again by selecting it from windows app list. Then it instead of resuming app from saved state it restarts it.
I think you are not using Single-Page Navigation for your app.
Please refer to Single-page navigation: the recommended model:
The script context is destroyed and must be initialized again. The app might receive system events but not handle them because the script context is being destroyed and reinitialized.
So the script context is already destroyed after you navigated to other page.
To fix the problem, the best solution is to make your app a single paged application. And navigate pages using PageControl. You can refer to Quickstart: Using single-page navigation to get started.
Update:
but when I use window.location.href for redirecting in main.js it closes app.
It's because you are using it in WinJS script. When you are leaving the page WinJS script context will be destroyed and thus executing the codes inside crash the app. To fix this you can use windows lifecycle API instead:
var roaming=Windows.Storage.ApplicationData.current.roamingSettings;
Windows.UI.WebUI.WebUIApplication.addEventListener("activated", function (args) {
if (args.detail[0].kind === activation.ActivationKind.launch) {
if (roaming.values["currentUri"]) {
window.location.href = roaming.values["currentUri"];
}
}
});
Windows.UI.WebUI.WebUIApplication.addEventListener("suspending", function (args) {
roaming.values["currentUri"] = window.location.href;
roaming.values["UserName"] = evt.srcElement.value;
//save the other information of the page here
});
Windows.UI.WebUI.WebUIApplication.addEventListener("resuming", function (args) {
var roam = Windows.Storage.ApplicationData.current.roamingSettings;
if (roam) {
if (roam["currentUri"])
{
window.location.href = roam["currentUri"];
}
}
}, false);
You can also refer to my demo.
Notes: If you don't use WinJS at all, just remove the reference. Loading WinJS library on every page is not efficient.
I have changed my main.js as :
(function () {
"use strict";
//No need of WinJS
var activation = Windows.ApplicationModel.Activation;
var roaming = Windows.Storage.ApplicationData.current.roamingSettings;
// For App Start Up
Windows.UI.WebUI.WebUIApplication.addEventListener("activated", function (args) {
if (args.detail[0].kind === activation.ActivationKind.launch) {
if (roaming.values["currentUri"]) {
if (roaming.values["UserName"])
{
localStorage.setItem("UserName", roaming.values["UserName"]);
window.location.href = roaming.values["currentUri"];
}
}
}
});
// For App Suspension
Windows.UI.WebUI.WebUIApplication.addEventListener("suspending", function (args) {
roaming.values["currentUri"] = window.location.href;
roaming.values["UserName"] = localStorage.getItem("UserName");
});
// For Resuming App
Windows.UI.WebUI.WebUIApplication.addEventListener("resuming", function (args) {
var roam = Windows.Storage.ApplicationData.current.roamingSettings;
if (roam) {
if (roam.values["currentUri"]) {
localStorage.setItem("UserName", roam.values["UserName"]);
window.location.href = roam.values["currentUri"];
}
}
}, false);
// not working backpressed event
Windows.UI.WebUI.WebUIApplication.addEventListener("backpressed", function (args) {
// to do
}, false);})();
Everything is working fine. But I dont know how to add back key press event without using winjs.
Can anyone suggest me?
How to add back key press event without winjs?

Javascript: OS-depending Redirects doesn't work for IOS

i've got a pretty simple Javascript for redirecting a specific URL to an app in Google-Play-Store/iOS-Store or show an URL for desktop users depending on the client's opersting system. For the ios case the redirect is not being executed, can anyone explain what the problem is? (alert before redirect is being executed properly!)
var playStoreUrl = "https://play.google.com/store/apps/details?id=xyz",
appStoreUrl = "https://itunes.apple.com/de/app/gxyz/id123456789?mt=8",
desktopUrl = "http://www.xyz.de/apps/";
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
}
};
if ( isMobile.Android() ) {
alert('os: android!');
window.location.href = playStoreUrl;
}
else if(isMobile.iOS()) {
alert('os: ios!');
window.location.href = appStoreUrl;
}
else {
alert('os: desktop!');
window.location.href = desktopUrl;
}
Solution: don't use the "?mt=8" parameter in the iOS-Appstore-Link and the redirect will work (and open the Appstore-App on your device)

How to launch window for install flash using javascript?

am using asp.net with Jquery, Javascript and flash.
Problem: I want to launch a window for install flash at client end(if not flash is not installed).
I used below javascript code to detect if flash is installed or not.
function detectFlash() {
var hasFlash = false;
try {
var fo = (navigator.mimeTypes && navigator.mimeTypes['application/x-shockwave-flash']) ? navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin : 0;
if (fo) {
hasFlash = true;
}
} catch (e) {
if (navigator.mimeTypes['application/x-shockwave-flash'] != undefined) {
hasFlash = true;
}
}
if (hasFlash) {
alert("flash is installed");
}
}
but using above code I got only true or false if installed or not. but if not installed then how can I launch window to install flash using Javascript/JQuery or asp.net
How can I achieve this?
Just make a redirect:
function detectFlash() {
var hasFlash = false;
try {
var fo = (navigator.mimeTypes && navigator.mimeTypes['application/x-shockwave-flash']) ? navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin : 0;
if (fo) {
hasFlash = true;
}
} catch (e) {
if (navigator.mimeTypes['application/x-shockwave-flash'] != undefined) {
hasFlash = true;
}
}
if (hasFlash) {
alert("flash is installed");
} else {
location = "http://www.adobe.com/software/flash/about/";
}
}
You can try to open it in a new tab (browsers may block such actions):
Open a URL in a new tab (and not a new window) using JavaScript
Enabling Flash plugin via JavaScript
Seriously, this is impossible (leave a comment if I'm wrong). Only the user is supposed to be able to enable this. Since this is a browser setting, this is different from a browser to another:
Chrome
Firefox
Internet Explorer
Unless the browsers don't expose a JavaScript API to enable this feature, we have this limitation.
You can redirect the page to this URL once hasFlash is false.
http://download.macromedia.com/pub/flashplayer/current/support/install_flash_player.exe

Categories