Check if ionic app is in dev serve mode(browser) - javascript

I use ionic serve to run my app on localhost.
how can I know when I'm in browser and not in android?
I tried:
navigator.platform // MacIntel
navigator.platforms // undefined
ionic.Platform.is('BROWSER') // false
navigator.userAgent // ...iPhone... => i'm in chrome device mode
Thank you!

There's probably more than one way to do it, but a simple one is that cordova will only be defined on Android/iOS so you could do
if (window.cordova) {
// running on device/emulator
} else {
// running in dev mode
}
Edit
Some text editors and TypeScript parsers may complain that Property 'cordova' does not exist on type 'Window'. In order to work around that, you can use the following:
if ((<any>window).cordova) {
// running on device/emulator
} else {
// running in dev mode
}
By explicitly casting to type any you can avoid transpiler errors, and still accomplish what you're trying to do.

I found I can use
ionic.Platform.platforms[0] == "browser"
to check if the application is running in a browser or not.
Important thing, ionic.Platform.platforms is set only after $ionicPlatform.ready event is fired.

Checking if window.location.hostname is equal to localhost will work too.
if(window.location.hostname === "localhost"){
return 'http://localhost:8100/api/';
} else {
return 'https://some-api.com/';
}

use
if(ionic.Platform.isWebView()){
console.log('i am in a browser webview!');
}
or
console.log(ionic.Platform.platform());
That will tell you what platform you are on. Webview or android or ios or whatever.

For now, in my Ionic 1 app (using last version 3.9.x, but with --type ionic1), ionic.Platform.platform() when i am in desktop is returning "linux", not "browser". And window.cordova now exists in browser, but you can check if window.cordova.platformId == 'browser'. It seems work here.

Just a little correction to Mirko N. answer.
Typescript will actually return error if you use cordova directly or as a child of window object.
The proper answer is to check if window has cordova as own property.
if(window.cordova) //returns error "Property 'cordova' does not exist on type 'Window'."
if(window.hasOwnProperty('cordova')) //Proper Check

Related

VueJS not building due to Android Javascript webView callback

I would like to have a WebView page callback to my Android app. I have successfully done this using vanilla HTML page. When I add the same JavaScript code to my VueJS app, it does not want to build, and gives me an ELIFECYCLE error.
In my Kotlin code, I have the following:
binding.webView.addJavascriptInterface(JavaScriptInterface(), "Android")
private inner class JavaScriptInterface {
fun showWallet(string: String) {
AppPreference.PREFERENCE_SCREEN_TYPE = Constants.SCREEN_USER_DASHBOARD
mainActivity.getNavController().navigate(R.id.action_placeOrder_to_userDashboardFragment)
}
}
Android is my JavaScript object I've declared, and the function is showWallet, which navigates the user to another fragment.
In my VueJS code, I have the following:
let devicedUsed = this.$store.state.devicedUsed;
if (devicedUsed === 'apple'){
window.webkit.messageHandlers.message.postMessage('backToWallet');
}else{ //is Android device
Android.showWallet('backToWallet');
}
The above callback works without any issues in vanilla HTML. My problem is the above code does not build, and I get an error that Android is not defined. It seems VueJS is looking for Android, which is only defined in the Kotlin code.
How do I get around this problem?
Use the window. prefix to tell the compiler that it's a global variable:
// BEFORE:
Android.showWallet('backToWallet')
// AFTER:
window.Android.showWallet('backToWallet')

Detecting microphone permissions using DetectRTC

I'm using a javascript library, DetectRTC, to detect if the browser can use microphone and other stuff.
if(DetectRTC.isWebsiteHasMicrophonePermissions){
//Is ok
}else{
//Can't use microphone
}
The site has the permissions to use the microphone, but DetectRTC.isWebsiteHasMicrophonePermissions is still false. So I tried to print the object on the console and I get that isWebsiteHasMicrophonePermissions is set to true. But when I print the variable alone, it changes to false again.
console.log(DetectRTC); //isWebsiteHasMicrophonePermissions: true
console.log(DetectRTC.isWebsiteHasMicrophonePermissions) //false
Is this a bug or something? How can I fix it?
As covered in the docs, you need to use DetectRTC.load() to wait for detecting audio/video input/output devices.
See this part of the docs for further info.
// This is too early
console.log(DetectRTC.hasMicrophone);
DetectRTC.load(() => {
// This is reliable
console.log(DetectRTC.hasMicrophone);
});
<script src="https://cdn.rawgit.com/muaz-khan/DetectRTC/master/DetectRTC.js"></script>

ngCordova getUUID() returns device is undefined

ngCordova getUUID() returns device is undefined
I am using Ionic framework to build a mobile app , i need to retrieve the device UUID
i used ngCordova using the minified version from here
ngCordova!
here is my main module
angular.module('starter', ['ionic','ngCordova'])
.controller('test',function($scope,$cordovaDevice){
$scope.uuid=$cordovaDevice.getUUID();
console.log($cordovaDevice)
})
$cordovaDevice is defined as object when using console.log but when using $cordovaDevice.getUUID() it gives me 'device is not defined' any help with that
Have you installed the cordovaDevice plugin using the command?
cordova plugin add org.apache.cordova.device
You should wait until device is ready...
document.addEventListener("deviceready", function() {
$scope.isOnline = $cordovaNetwork.isOnline();
$scope.UUID = $cordovaDevice.getUUID();
}, false);
I solved this by calling $scope.$apply() after the call to $cordovaDevice.getUUID()
$ionicPlatform.ready(function() {
if(ionic.Platform.isAndroid()) {
$scope.account.imei = $cordovaDevice.getUUID();
$scope.$apply();
}else {//For ionic serve
$scope.account.imei = '12345';
console.log($scope.account.imei);
}
});
From the official documentation http://ngcordova.com/docs/common-issues/, the cordova plugin returns a promise.
$ionicPlatform.ready(function() {
$cordovaPlugin.someFunction().then(success, error);
});
You've stated ngCordova correctly as a module dependency. I think all you need to do is inject $cordovaDevice into your controller with the full array syntax
.controller('test',['$scope', '$cordovaDevice', function($scope, $cordovaDevice){
$scope.uuid=$cordovaDevice.getUUID();
}])
If that doesn't work have you checked that the the plugin is loading first?
This error is occurring because you are asking for a device's details, whilst you are developing on your machine.
Look at the functions. None of them will return a suitable value on your dev env. Also Cordova is built for mobile devices - they haven't created a set of handlers for local dev.
Returns the whole device object.
getDevice()
Returns the Cordova version.
getCordova()
Returns the name of the device's model or product.
getModel()
Returns the device's operating system name.
getPlatform()
Returns the device's Universally Unique Identifier.
getUUID()
Returns the operating system version.
getVersion()

Phonegap (Android) - database changeVersion not functioning

If I take a database object (db) and open it with the command
var db = window.openDatabase("phr", "", "Cognovant PHR", 25000000);
// This should open whatever database is created, otherwise spawn one with a blank
// version number ("")
and then later do:
db.changeVersion(db.version, "2"); // Update database to version 2
console.log(db.version); //Should return "2", instead returns previous version of database
This code, line-for-line works flawlessly (almost better than I had hoped) on iOS, but constantly fails to change the database version on Android.
If there's some better way to do this, or some alternative way that needs done on Android, I would be greatly appreciative of the information.
This is actually pretty simple to solve.
Simply change the 2 argument version of db.changeVersion to the 3 argument version. Example:
db.changeVersion(db.version, "2", function () {console.log("foobar")});
And it will work.
This problem also occurs in Android 2.2.
09-28 07:15:14.954: E/Web Console(280): TYPE_MISMATCH_ERR: DOM Exception 17: The type of an object was incompatible with the expected type of the parameter associated to the object. at file:///android_asset/www/devbar/03%20db.js:158
The only solution I see is to workaround with my own version management.
Please go through below link, describes the way to implement the database Version control.
http://developer.apple.com/library/safari/#documentation/iphone/conceptual/safarijsdatabaseguide/UsingtheJavascriptDatabase/UsingtheJavascriptDatabase.html
i am able to do success operation with all 2.3.x devices, but with 4.x.x android device getting issue like 'unable to call method changeVersion' and saying method is undefined.
for time being i am using code as below,
if (db.changeVersion) {
db.changeVersion(oldVer, curVer, upgradeTableStructure, errorHandler, successDataHandler);
} else {
createTableStructure(db);//If Not exist for first time for 4.x.y devices
console.log('version changes not possible in this browser version.');
}
but this is not the right solution for the Current Problem, please suggest some solution.

Log to Firefox Error Console from JavaScript

Is it possible to add messages to the built-in error console of Firefox from JavaScript code running in web pages?
I know that I there's Firebug, which provides a console object and its own error console, but I was looking for a quick fix earlier on and couldn't find anything.
I guess it might not be possible at all, to prevent malicious web pages from spamming the log?
If you define a global function that checks for the existence of window.console, you can use Firebug for tracing and still plays nice with other browsers and/or if you turn Firebug's console tracing off:
debug = function (log_txt) {
if (typeof window.console != 'undefined') {
console.log(log_txt);
}
}
debug("foo!");
You cannot write to the console directly from untrusted JavaScript (e.g. scripts coming from a page). However, even if installing Firebug does not appeal to you, I'd recommend checking out Firebug Lite, which requires no installation into the browser (nor, in fact, does it even require Firefox). It's a script which you can include into any web page (even dynamically), which will give you some basic Firebug functionality (such as console.log()).
Yes, you can =P
function log(param){
setTimeout(function(){
throw new Error("Debug: " + param)
},0)
}
//Simple Test:
alert(1)
log('This is my message to the error log -_-')
alert(2)
log('I can do this forever, does not break')
alert(3)
Update to a real function
This is a simple hack, just for fun.
window.console is undefined in Firefox 4 beta 6 even if Firebug 1.6X.0b1 is enabled and open, probably because of privilege issues that others discuss. However, Firefox 4 has a new Tools > Web Console, and if this is open you have a window.console object and untrusted JavaScript code on the page can use console.log(). The Web Console is in flux (see https://wiki.mozilla.org/Firefox/Projects/Console), you may need to change settings named devtools.* in about:config , YMMV.
I would just install Firebug and use console.log. If you can't do that, though, you can always throw an error:
throw "foobar";
throw new Error("bazquux");
Of course, this will break you out of the code that you're currently executing, so you can't use it for detailed logging, but if you can work around that I think it's the only way to get something logged out of the box.
AFAIK, it is not possible. But if you are interested in how extensions in Firefox interact with the error console, check this out.
This function does not require any extension nor library. However it grants full privileges to the relevant website. No worries since you are the one developing it, right?
// Define mylog() function to log to Firefox' error console if such a
// thing exists
function defineMyLog()
{
// Provide a useless but harmless fallback
mylog = function(msg) { };
// return; // disable in production
if (typeof(netscape) === "undefined") {
// alert("Logging implemented only for Firefox");
return;
}
// The initial auth popup can be avoided by pre-setting some magic user_pref
// ( "capability.principal.codebase.p0.granted", "UniversalXPConnect"), etc.
try {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
} catch (e) { // User has denied privileges
// alert(e.name + ": " + e.message);
return;
}
ffconsoleService = Components.classes["#mozilla.org/consoleservice;1"]
.getService(Components.interfaces.nsIConsoleService);
mylog = function (msg)
{
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
ffconsoleService.logStringMessage(new Date().toLocaleTimeString() + ": " + msg);
}
mylog("Firefox logging function has been defined");
// window.open("javascript:"); // this URL does not work anymore?
}
If you're interested, check out a script I wrote -- it's a "cheap" Firebug replacement that doesn't interfere with any normal console (like Safari or Chrome) but does extend it with almost all the Firebug methods:
http://code.google.com/p/glentilities/
Look under the hood and you'll see what I mean by "cheap". :-)
Combine it with YUI or json.org's JSON serializers to sorta replicate console.dir.
Firebug and Firebug Lite are definitely nicer GUIs, but I use my home-grown one all the time to retain logging safely even for production code -- without constant commenting & un-commenting,

Categories