Simple Android versus iOS detection in WordPress theme - android

I am trying to edit my WordPress theme file to show one ad code if an Android device is detected, another set of code if iOS.
The code is in the format:
<script type="text/javascript" src="//xxxxxxxx.js"></script>
I have tried several previous answers, such as the following:
Detecting iOS / Android Operating system
Detect Android phone via Javascript / jQuery
What is the best way to detect a mobile device in jQuery?
All of which are slightly different and cause my page to not load (blank page).
Could someone please give me a hand and post the full simplest/fastest code to simply detect Android versus iOS and do nothing for anything else (i.e. a Windows PC). Something I can just copy and paste into the theme files where I want it.
Edit: I also tried things like the following to no avail (this was exactly what I pasted into the WordPress theme file, without the xxx and including proper reference to external .js file:
<?php var isAndroid = /(android)/i.test(navigator.userAgent);
if (isAndroid) {?>
<script type="text/javascript" src="xxxxxxx.js"></script>
<?php } ?>
and
<?php function getMobileOperatingSystem() {
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
if( userAgent.match( /Android/i ) )
{?>
<script type="text/javascript" src="//xxxxxxx.js"></script>
<?php}
} ?>

[EDIT]
Try changing your code to the below snippet:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
function isAndroid() {
return /Android/i.test(navigator.userAgent);
}
function isIOS() {
return /iPhone|iPad|iPod/i.test(navigator.userAgent);
}
if(isAndroid()) { $.getScript("//cdn.bounce.bar/xxxx.js"); }
</script>
The reason what you tried above doesn't work is because you are trying to put javascript code into a PHP function when the interpreter is looking for PHP code.
If you have direct access to the HTML page, then you could do something like the following. This code is taken almost directly from Detect if browser is running on an Android or iOS device.
<script>
function isAndroid() { return /Android/i.test(navigator.userAgent); }
function isIOS() { return /iPhone|iPad|iPod/i.test(navigator.userAgent); }
</script>
Remember that PHP code is generally server side and javascript code is generally client side. I would try to load the script using Javascript depending on the OS type. Something like this might work if you are using Jquery:
<script>
if(isAndroid()) {
$.getScript("//xxxxxxx.js");
}
</script>
I'm still not exactly sure what you are trying to do, but let me know if this doesn't work and provide more details, and I'll try to help out.

You could do this
if(/Android/i.test(navigator.userAgent) ) {
..............
}
else if(/iPhone/iPad/i.test(navigator.userAgent) ){}

Related

How to loop using Mustache in my ktor kotlin android project

I am making an android application with Kotlin using the framework Ktor where the android device act as the server and you can connect to it using your browsers in other devices.
I have been able to get to the spot where my .hbs file (which is the template for creating a html page) displays all data in the browser.
When I pass single data like String, Int, Bool from the backend to this .hbs page.
But when I try to pass a list or arraylist to the .hbs page and loop through it, I cannot displays the content from the loop.
This is how I set up my templates
fun Application.configureTemplating(){
install(Mustache){
mustacheFactory = DefaultMustacheFactory("templates")
}
}
This is how I set up my routing
fun Application.configureRouting() {
routing {
get("/") {
call.respondRedirect("web")
}
route("web") {
get{
val directoryFiles = DataManager.getRawData(Const.ROOT_FOLDER_KEY)
call.respond(MustacheContent("index.hbs", mapOf("directoryFiles" to directoryFiles)))
}
}
}
}
This is my .hbs file
<html>
<head>
</head>
<body>
<h3>Folders</h3>
<div class="container">
{{#directoryFiles}}
<p>{{name}}</p>
{{/directoryFiles}}
</div>
</body>
</html>
My "directoryFiles" prints
[{"extension":"","fileType":"FOLDER","name":"Pictures","path":"\/storage\/emulated\/0\/Pictures","sizeInMB":0.003326416015625,"subFiles":5},{"extension":"","fileType":"FOLDER","name":"Android","path":"\/storage\/emulated\/0\/Android","sizeInMB":0.003326416015625,"subFiles":3}].
when I try to debug it.
When I try to display the only the list in the browser it shows
, but I try to loop through it and display it's content, the content doesn't show and it does not display an errors either.
This is my mustache gradle dependency and the ktor version is 2.0.1
implementation("io.ktor:ktor-server-mustache:$ktor_version")
This is the project hierarchy
I have found the answer to the question. The bug was because I was using an array of json, instead of using an array of kotlin data class.
My list should look like
[FileModel(path=/storage/emulated/0/Pictures, fileType=FOLDER, name=Pictures, sizeInMB=0.003326416015625, extension=, subFiles=5), FileModel(path=/storage/emulated/0/Android, fileType=FOLDER, name=Android, sizeInMB=0.003326416015625, extension=, subFiles=3)]
And the index.hbs should look like this
<html>
<body>
{{#directoryFiles}}
<h1>File {{name}}</h1>
{{/directoryFiles}}
</body>
</html>

How To Access Files on Android Device Using Ionic Framework

I was working through the Ionic tutorial for using the Cordova Camera API.
http://learn.ionicframework.com/formulas/cordova-camera/
Far as I can tell everything is working correctly with the Camera API functions, but I cannot get my image to display back into the view.
I am able to return a file URI, but when I attempt to put it to the ng-src I get nothing in the view. I am assuming that the application/code cannot access the file location?
My config:
.config(function($stateProvider, $urlRouterProvider, $compileProvider) {
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|file|blob|content):|data:image\//);
...
The function in my controller:
$scope.getPhoto = function() {
Camera.getPicture().then(function(imageURI) {
console.log(imageURI);
$scope.cameraPic = imageURI;
}, function(err) {
$scope.cameraPic = "error";
console.err(err);
});
};
My view:
<ion-view>
<ion-content>
<div class="form-group padding-top">
<button class='button button-positive' data-ng-click="getPhoto()">
Take Photo
</button>
</div>
<div class="item item-image">
<img ng-src="{{cameraPic}}"/>
</div>
{{cameraPic}}
</ion-content>
</ion-view>
This appears to be the recommended method by the tutorial, and is also repeated on this thread. It sounds like it should work without using a Cordova file service implementation. I have found one such implementation which I guess I could use, but am I missing something here?
EDIT
Using chrome://inspect/#devices, I was able to look into the Webview/Console. I also rebuilt the project, just to see if that would help.
Definitely looking like a local file access issue.
As it turns out, this is an issue unique to using the emulator. I finally found the following on the ngCordova project:
NOTE: The camera API only works on a real device, and not in the
emulator.
Source: http://ngcordova.com/docs/plugins/camera/
This led me to test the code on an actual device using the USB debugger, where the file is accessed by the application and shared with the view as expected. This should be noted as a quirk of the library.

Phonegap Camera view inside html(Div) in android/Ios [duplicate]

Is there a view of showing the live camera view inside html ( e.g. embedded in a div ) before we snap a picture using JavaScript? I have tried PhoneGap but it totally starts a new camera app and totally moves away from my html web app before returning to it. I need something embedded in my app
Thanks
You can install mbppower/CordovaCameraPreview plugin (for android,ios) in your Cordova/phonegap application that allows camera interaction from HTML code. A really amazing plugin it is..
You can access Features such as:
Start a camera preview from HTML code.
Drag the preview box.
Set camera color effect (Android and iOS),Send the preview box to back of the HTML content,Set a custom position for the camera preview box,Set a custom size for the preview box and Maintain HTML interactivity.
Or you can also use donaldp24/CanvasCamera Plugin for your application if it fits to your requirements.Its supported in both android and iOS platforms. I have observed, for iOS its working fine but in android it isn't working.
Now you can install CordovaCameraPreview plugin through Online PhoneGap too. So without using CLI you can directly use it through this by adding
<gap:plugin name="com.mbppower.camerapreview" version="0.0.8" source="plugins.cordova.io" />
in your config.xml file and create ApplicationTemplate.apk/.ipa. For more information regarding this you can ask me. Happy to help.
UPDATE:10th Oct 2017
It used to work well during that time but, donaldp24/CanvasCamera is no longer maintained and currently fails build with the latest Cordova version.
I did it for one of my projects. Check out navigator.getUserMedia(). There are a tonne of things you can do with your webcam and browser, including AR games! Here's just a basic example:
HTML:
<html>
<head>
</head>
<body>
<form><input type='button' id='snapshot' value="snapshot"/></form>
<video autoplay></video>
<canvas id='canvas' width='100' height='100'></canvas>
<script type="text/javascript" src="findit.js"></script>
</body>
</html>
findit.js
var onFailSoHard = function(e)
{
console.log('failed',e);
}
window.URL = window.URL || window.webkitURL ;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
var video = document.querySelector('video');
if(navigator.getUserMedia)
{
navigator.getUserMedia({video: true},function(stream) {
video.src = window.URL.createObjectURL(stream);
},onFailSoHard);
}
document.getElementById('snapshot').onclick = function() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(video,0,0);
}
Live Demo:
A personal project
More Resources, this is what I used:
Webcam Access
Update:
This solution is valid only for front camera if our device has one. It's basically a "webcam" solution. Not sure if it'll work for your case. Just in case, check out the resources.
You can use camera.getPicture from cordova-plugin-camera or navigator.device.capture.captureVideo from cordova-plugin-media-capture.
var getUserMedia = navigator.getUserMedia
|| navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia
|| navigator.msGetUserMedia
|| navigator.device.capture.captureVideo
|| navigator.camera
|| camera.getPicture;
Hope it helps.
There is no direct access to the Camera app using javascript. You can either write a custom PhoneGap (Cordova) plugin to do that.

Showing camera view inside html in android and then snap a picture

Is there a view of showing the live camera view inside html ( e.g. embedded in a div ) before we snap a picture using JavaScript? I have tried PhoneGap but it totally starts a new camera app and totally moves away from my html web app before returning to it. I need something embedded in my app
Thanks
You can install mbppower/CordovaCameraPreview plugin (for android,ios) in your Cordova/phonegap application that allows camera interaction from HTML code. A really amazing plugin it is..
You can access Features such as:
Start a camera preview from HTML code.
Drag the preview box.
Set camera color effect (Android and iOS),Send the preview box to back of the HTML content,Set a custom position for the camera preview box,Set a custom size for the preview box and Maintain HTML interactivity.
Or you can also use donaldp24/CanvasCamera Plugin for your application if it fits to your requirements.Its supported in both android and iOS platforms. I have observed, for iOS its working fine but in android it isn't working.
Now you can install CordovaCameraPreview plugin through Online PhoneGap too. So without using CLI you can directly use it through this by adding
<gap:plugin name="com.mbppower.camerapreview" version="0.0.8" source="plugins.cordova.io" />
in your config.xml file and create ApplicationTemplate.apk/.ipa. For more information regarding this you can ask me. Happy to help.
UPDATE:10th Oct 2017
It used to work well during that time but, donaldp24/CanvasCamera is no longer maintained and currently fails build with the latest Cordova version.
I did it for one of my projects. Check out navigator.getUserMedia(). There are a tonne of things you can do with your webcam and browser, including AR games! Here's just a basic example:
HTML:
<html>
<head>
</head>
<body>
<form><input type='button' id='snapshot' value="snapshot"/></form>
<video autoplay></video>
<canvas id='canvas' width='100' height='100'></canvas>
<script type="text/javascript" src="findit.js"></script>
</body>
</html>
findit.js
var onFailSoHard = function(e)
{
console.log('failed',e);
}
window.URL = window.URL || window.webkitURL ;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
var video = document.querySelector('video');
if(navigator.getUserMedia)
{
navigator.getUserMedia({video: true},function(stream) {
video.src = window.URL.createObjectURL(stream);
},onFailSoHard);
}
document.getElementById('snapshot').onclick = function() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(video,0,0);
}
Live Demo:
A personal project
More Resources, this is what I used:
Webcam Access
Update:
This solution is valid only for front camera if our device has one. It's basically a "webcam" solution. Not sure if it'll work for your case. Just in case, check out the resources.
You can use camera.getPicture from cordova-plugin-camera or navigator.device.capture.captureVideo from cordova-plugin-media-capture.
var getUserMedia = navigator.getUserMedia
|| navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia
|| navigator.msGetUserMedia
|| navigator.device.capture.captureVideo
|| navigator.camera
|| camera.getPicture;
Hope it helps.
There is no direct access to the Camera app using javascript. You can either write a custom PhoneGap (Cordova) plugin to do that.

jQueryMobile running on Android / PhoneGap refuses .load / .ajax

I really hate asking questions that I feel were asked a thousand times before. This is one of those questions I feel others must have encountered, but having searched stack overflow, none of the supposed solutions work for me so I must be doing something wrong.....
I have an extremely simple app setup. index.htm, and terms.htm. There is some textual data in test.htm. I set both $.support.cors = true; and $.mobile.allowCrossDomainPages = true; at the appropriate time after stuff has loaded.
At first I tried loading terms.htm's data into an element within index using $('#elementid').load('terms.htm'); (both test and index are in the same root /assets/www/ directory, and my webview loads index oncreate) but absolutely nothing was happening. So I opted to try .ajax so that I could at least get an error message, and all I get is 'error'. Surely, it is possible to load local textual assets with JQ on DroidGap?
$('#header').load('terms.htm');
$.ajax({
type:"GET",
timeout:10000,
async: false,
url: "terms.htm",
success: function(data) {
$('#header').html(data);
},
error: function(xhr,msg){
alert( msg);
}
});
I'm not 100% sure, but I think it's a problem with ICS 4.0.3. On 4.0.2 ajax seems to work completely fine, but for me too on 4.0.3, no ajax. Like you, I've tried everything, and nothing has worked..
I'm using PhoneGap btw. Ajax works fine in the standard browser, but not in a PhoneGap app..
If you are running your application in Chrome
Then you need to disable-web-security and enable loading local files see Cross-domain requests using PhoneGap and jQuery doesn't work
Else if Safari or simulator or web-server
Then it should work
See this link. I had the same problem and this solved it. Also, I think they fixed it in 1.6.0 but I am now seeing the same issue on iOS with PhoneGap 1.6.1.
it is just a long shot, but you say "I set both $.support.cors = true; and $.mobile.allowCrossDomainPages = true; at the appropriate time after stuff has loaded.". The jQuery mobile documentation says you have to set your global configuration before you load JQM:
Because the mobileinit event is triggered immediately, you'll need to bind your event
handler before jQuery Mobile is loaded. Link to your JavaScript files in the following
order:
<script src="jquery.js"></script>
<script src="custom-scripting.js"></script>
<script src="jquery-mobile.js"></script>
In your case this would be:
<script src="jquery.js"></script>
<script>
$(document).bind("mobileinit", function(){
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
});
</script>
<script src="jquery-mobile.js"></script>
Like I said, just a guess ...

Categories

Resources