CSS: -webkit-touch-callout alternatives for android - android

Is there any alternative for -webkit-touch-callout, which works on Android based mobiles.
I'm trying to disable the long touch popup in mobile devices.
I've tried to bind jQuerys taphold event to return false; but no luck...
Any idea?
Thanks!

<!DOCTYPE html>
<html>
<head>
<script>
function absorbEvent_(event) {
var e = event || window.event;
e.preventDefault && e.preventDefault();
e.stopPropagation && e.stopPropagation();
e.cancelBubble = true;
e.returnValue = false;
return false;
}
function preventLongPressMenu(node) {
node.ontouchstart = absorbEvent_;
node.ontouchmove = absorbEvent_;
node.ontouchend = absorbEvent_;
node.ontouchcancel = absorbEvent_;
}
function init() {
preventLongPressMenu(document.getElementById('theimage'));
}
</script>
</head>
<body onload="init()">
<img id="theimage" src="http://www.google.com/logos/arthurboyd2010-hp.jpg" width="400">
</body>
</html>
Source: Disabling the context menu on long taps on Android

Related

Ionic Framework and AngularJS - How to read mobile contacts into application

Below is the code I have tried. When I execute the code below it appears as when I click a button in my application and it is opening device phone book and displaying contacts. When I click on any contact it is picked by application but it should not open device address book but when clicked it should display the contacts of my device in my application. Can anyone suggest me how to do this?
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, r-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="starter" ng-controller="AppCtrl" class="platform-android platform-cordova platform-webview">
<ion-pane>
<ion-header-bar class="bar-stable">
<button class="button" ng-click="pickContact()">Contacts</button>
<h1 class="title">All Contacts</h1>
</ion-header-bar>
<ion-content>
<div class="list">
<a class="item item-thumbnail-left" ng-repeat="contact in data.selectedContacts">
<img src="{{contact.photos[0].value}}" ng-if="contact.photos.length > 0">
<h2>{{contact.displayName}}</h2>
<p ng-if="contact.emails.length > 0">{{contact.emails[0].type}} : {{contact.emails[0].value}}</p>
<p ng-if="contact.phones.length > 0">{{contact.phones[0].type}} : {{contact.phones[0].value}}</p>
</a>
</div>
<p class="padding"></p>
</ion-content>
</ion-pane>
</body>
</html>
Javascript:
angular.module('starter', ['ionic'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.service("ContactsService", ['$q',
function($q) {
var formatContact = function(contact) {
return {
"displayName": contact.name.formatted || contact.name.givenName + " " + contact.name.familyName || "Unknown Person",
"emails": contact.emails || [],
"phones": contact.phoneNumbers || [],
"photos": contact.photos || []
};
};
var pickContact = function() {
var deferred = $q.defer();
if (navigator && navigator.contacts) {
navigator.contacts.pickContact(function(contact) {
deferred.resolve(formatContact(contact));
});
} else {
deferred.reject("Hurray!!!!...... No contacts in desktop browser");
}
return deferred.promise;
};
return {
pickContact: pickContact
};
}
])
.controller("AppCtrl", ['$scope', 'ContactsService',
function($scope, ContactsService) {
$scope.data = {
selectedContacts: []
};
$scope.pickContact = function() {
ContactsService.pickContact().then(
function(contact) {
$scope.data.selectedContacts.push(contact);
console.log("Selected contacts=");
console.log($scope.data.selectedContacts);
},
function(failure) {
console.log("Hurray!!!!...... Failed to pick a contact");
}
);
}
}
])
You could try using $cordovaContacts which is a part of the ngCordova (ngCordova needs to be installed). You can install in your app with the command cordova plugin add cordova-plugin-contacts. Then there is a simple function to getting all contacts in your contacts list.
$scope.getAllContacts = function() {
$cordovaContacts.find({filter: '',multiple:true}).then(function(allContacts) {
$scope.contacts = allContacts;
});
};
Note: It seems to be so that the find() function in $cordovaContacts can not be empty. Include ie. a filter in there for it to work.
EDIT:
This is a demonstration of the general structure and functions which you need to make the ngCordova contacts plugin to work.
Here's all my code you'll need in a JSFiddle: https://jsfiddle.net/thepio/osjppoqu/
And then I just call the getAllContacts function using a button click in my app.html file like this:
<button type="button" ng-click="getAllContacts()" class="button button-block button-positive">Get contacts</button>
REMEMBER it only works on a real device, probably not even emulator (haven't tested though). Include the ngCordova in your module. If you're calling the contacts plugin without a click or something remember that it is required that it's only called AFTER the device is ready. In Ionic you can do this with the following:
$ionicPlatform.ready(function() {
// Call the plugin here
});

Unable to connect to xmpp server in phonegap with openfire server using strophe.js

I am new to the phonegap.Iam using coredova latest version 2.9.0 for developing chatting application by connecting to xmpp server with open fire server..I have been searching for the related storph.js code in phonegap since last 2 days.I didn't get the running code in phonegap,getting status '1' means connecting..can anyone helps...thanks in advace.
<html>
<head>
<title>
phonegap xmpp tutorial
</title>
</head>
<script type="text/javascript" charset="utf-8" src="coredova-2.9.0.js"></script>
<script type="text/javascript" charset="utf-8" src="strophe.js"></script>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js'></script>
<script>
function connect() {
var username="xxx";
var HOST_DOMAIN="xxx";
var password="xxx";
var BOSH_SERVICE = "xxxxx";
connection = new Strophe.Connection(BOSH_SERVICE);
connection.connect(username + "#" + HOST_DOMAIN, password, onConnect);
}
function onConnect(status) {
alert(status);
if (status == Strophe.Status.CONNECTED) {
alert("connected");
}else if (status == Strophe.Status.DISCONNECTED) {
console.log("Strophe is disconnected.");
}
}
</script>
<body>
<button onclick="connect();">click</button>
</body>
</html>
See if you have properly configured the URL (BOSH_SERVICE), Openfire default URL is
"127.0.0.1:7070/http-bind/"
It would be good to use a console where show Strophe sends messages to the XMPP server and receives from the server to debug(look at "Exploring the XMPP Protocol: A Debugging Console"), It can be helpful the book “Professional XMPP - Programming with JavaScript and jQuery”.
Basic strophe example:
<!DOCTYPE html>
<html>
<head>
<title>Strophe.js Basic Example</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js'></script>
<script src='strophe.js'></script>
<script>
//URL server openfire, by default 'http://Server-IP:7070/http-bind/'
var BOSH_SERVICE = 'http://bosh.metajack.im:5280/xmpp-httpbind'
var connection = null;
function log(msg)
{
$('#log').append('<div></div>').append(document.createTextNode(msg));
}
function rawInput(data)
{
log('RECV: ' + data);
}
function rawOutput(data)
{
log('SENT: ' + data);
}
function onConnect(status)
{
if (status == Strophe.Status.CONNECTING) {
log('Strophe is connecting.');
} else if (status == Strophe.Status.CONNFAIL) {
log('Strophe failed to connect.');
$('#connect').get(0).value = 'connect';
} else if (status == Strophe.Status.DISCONNECTING) {
log('Strophe is disconnecting.');
} else if (status == Strophe.Status.DISCONNECTED) {
log('Strophe is disconnected.');
$('#connect').get(0).value = 'connect';
} else if (status == Strophe.Status.CONNECTED) {
log('Strophe is connected.');
connection.disconnect();
}
}
$(document).ready(function () {
connection = new Strophe.Connection(BOSH_SERVICE);
connection.rawInput = rawInput;
connection.rawOutput = rawOutput;
$('#connect').bind('click', function () {
var button = $('#connect').get(0);
if (button.value == 'connect') {
button.value = 'disconnect';
connection.connect($('#jid').get(0).value, $('#pass').get(0).value, onConnect);
} else {
button.value = 'connect';
connection.disconnect();
}
});
});
</script>
</head>
<body>
<div id='login' style='text-align: center'>
<form name='cred'>
<label for='jid'>JID:</label>
<input type='text' id='jid'>
<label for='pass'>Password:</label>
<input type='password' id='pass'>
<input type='button' id='connect' value='connect'>
</form>
</div>
<hr>
<div id='log'></div>
</body>
</html>
Check if the http binding is enabled in your server settings. You can confirm that by navigating to "server-ip:7070" with your web browser. A message like this one "Openfire HTTP Binding Service" is shown when the HTTP binding is enabled and listening at that port (7070 is the default).
To change the HTTP binding settings just open the server settings web interface and navigate to "Server->Server Settings->HTTP Binding".

How to access the specific camera on mobile phone through html5

When I use html5 'getUserMedia' API to access acamera on the android(4.0) phone, it comes out "front camera", but I want to open "back camera". Sample code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Html5 Mobile Carema</title>
<script src="js/jquery.js"></script>
<script>
$(document).ready(init);
function init() {
try {
window.URL = window.URL || window.webkitURL || window.msURL
|| window.oURL;
navigator.getUserMedia = navigator.getUserMedia
|| navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia || navigator.msGetUserMedia;
navigator.getUserMedia({
video : true
}, successsCallback, errorCallback);
} catch (err) {
// Tries it with old spec of string syntax
navigator.getUserMedia('video', successsCallback, errorCallback);
}
$(":button").click(function() {
slap();
});
}
function slap() {
var video = $("#myVideo")[0];
var canvas = capture(video);
$("#result").empty();
$("#result").append(canvas);
//alert();
var imgData = canvas.toDataURL('image/png;base64,');
//var imgData = canvas.toDataURL("image/png");
var imgData = imgData.substring(22);
//blb = dataURItoBlob(imgData);
//sendMsg(blb);
}
function errorCallback(err) {
}
function successsCallback(stream) {
$("#myVideo").attr("src", window.webkitURL.createObjectURL(stream));
}
function capture(video) {
var canvas = document.createElement('canvas');
var width = video.videoWidth;
var height = video.videoHeight;
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
var context = canvas.getContext('2d');
context.drawImage(video, 0, 0, 160, 120);
return canvas;
}
</script>
</head>
<body>
<video id="myVideo" autoplay="autoplay"></video>
<br> <input type="button" value="capture" />
<br><div id="result" style="width: 145px"></div>
<div>
<p id="resultMsg" style="color: red"></p>
<p id="decodeTime" style="color: green"></p>
</div>
</body>
</html>
I don't know how to access specific camera on android phone, anyone who knows? thanks
There is now the ability to specify a camera in the latest specification with the facingMode property: http://www.w3.org/TR/mediacapture-streams/#idl-def-VideoFacingModeEnum
This property is an optional part of the MediaStreamConstraints object that is the first argument of the getUserMedia method.
Here's a simplified example from the spec:
var supports = navigator.mediaDevices.getSupportedConstraints();
if (!supports["facingMode"]) {
// Handle lack of browser support if necessary
}
var gotten = navigator.mediaDevices.getUserMedia({
video: {
facingMode: {exact: "environment"}
}
});
The value environment means the back camera of the device. Other values are user, left and right.
Note that support for this varies depending on the browser/browser version.
See function gotSources(sourceInfos) in the code below
<!--
Based on Motion Detector Demo Created by Ákos Nikházy.
If you use this app please link this demo http://motion-detector.nikhazy-dizajn.hu/
-->
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Frame capture demo</title>
</head>
<body>
<header>
<h1>Motion Detection</h1>
<h4>with HTML5 API using .getUserMedia()</h4>
</header>
<video autoplay></video>
<hr>
<canvas id="savePhoto"></canvas>
<script>
function hasGetUserMedia() {
//returns true if supported
return !!(navigator.getUserMedia || navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia || navigator.msGetUserMedia);
}
function onSuccess(stream) {
//If we can stream from camera.
var source;
//Get the stream. This goes to the video tag
if (window.URL) {
source = window.URL.createObjectURL(stream);
} else if (window.webkitURL) {
source = window.webkitURL.createObjectURL(stream);
} else {
source = stream; // Opera and Firefox
}
//Set up video tag
video.autoplay = true;
video.src = source;
//We try to find motion in every X second
setInterval(function() {
motionDetector();
}, sampling);
}
function onError() {
//if we fail (not supported, no camera etc.)
alert('No stream, no win. Refresh.');
}
function saveImage(canvasToSave) {
//create image from canvas
dataUrl = canvasToSave.toDataURL();
imageFound = document.createElement('img');
imageFound.src = dataUrl;
document.body.appendChild(imageFound);
}
function motionDetector() {
ctxSave.drawImage(video, 0, 0, savePhoto.width, savePhoto.height);
}
/*After all those functions lets start setting up the program*/
//Set up elements. Should be a ini() but I don't care right now
var video = document.querySelector('video'); //the video tag
var savePhoto = document.getElementById('savePhoto'); //the possible saved image's canvas
var ctxSave = savePhoto.getContext('2d'); //the latest image from video in full size and color
var sampling = 1000; //how much time needed between samples in milliseconds
var videoSourceInfo = null;
//We need this so we can use the videoWidth and ...Height, also we setup canvas sizes here, after we have video data
video.addEventListener("loadedmetadata", function() {
console.log(video.videoWidth + ":" + video.videoHeight)
savePhoto.width = video.videoWidth;
savePhoto.height = video.videoHeight;
});
function start() { //Start the whole magic
if (hasGetUserMedia()) {
//it is working?
navigator.getUserMedia
|| (navigator.getUserMedia = navigator.mozGetUserMedia
|| navigator.webkitGetUserMedia
|| navigator.msGetUserMedia);
var videoSourceInfoId = videoSourceInfo.id;
var constraints = {
video : {
optional: [{sourceId: videoSourceInfoId}]
},
toString : function() {
return "video";
}
};
navigator.getUserMedia(constraints, onSuccess, onError);
} else {
//no support
alert('getUserMedia() is not supported in your browser. Try Chrome.');
}
}
function gotSources(sourceInfos) {
for (var i = sourceInfos.length-1 ; i >= 0; i--) { // get last camera index (supposed to back camera)
var sourceInfo = sourceInfos[i];
if (sourceInfo.kind === 'video') {
videoSourceInfo = sourceInfo;
console.log('SourceId: ', videoSourceInfo.id);
start();
break;
} else {
console.log('Some other kind of source: ', sourceInfo);
}
}
}
if (typeof MediaStreamTrack === 'undefined') {
alert('This browser does not support MediaStreamTrack.\n\nTry Chrome Canary.');
} else {
MediaStreamTrack.getSources(gotSources); // async task
}
</script>
</body>
</html>
Hi I think this works with you
<script>
var gum = mode =>
navigator.mediaDevices.getUserMedia({video: {facingMode: {exact: mode}}})
.then(stream => (video.srcObject = stream))
.catch(e => log(e));
var stop = () => video.srcObject && video.srcObject.getTracks().forEach(t => t.stop());
var log = msg => div.innerHTML += msg + "<br>";
</script>
<button onclick="stop();gum('user')">Front</button>
<button onclick="stop();gum('environment')">Back</button>
<div id="div"></div><br>
<video id="video" height="320" autoplay></video>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
facingMode??
https://github.com/webrtcHacks/adapter/issues/820
https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/facingMode

Hide URL in browser on Android 2.3 using HTML/javascript

Does somebody know how to hide URL on Android (like full screen) using HTML/javascript?
On iPad (Safari) this is simple and can be done using only a few meta tags.
I have tried something like that:
$(document).ready(function () {
scrollTo(0, 1);
});
But, on Motorola T1, the URL bar is still displayed :(
None of any solution above worked for me on Samsung S3 mini phone with Android 4.1.1
But I have followed the mentioned url and there was the absolutely right solution.
Thanks for it.
https://gist.github.com/1183357
See Fresheyeball's implementation. That works perfectly in portrait and landscape mode as well.
I just copy here my full example:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function() {
hideAddressBar();
});
function hideAddressBar() {
if (navigator.userAgent.match(/Android/i)) {
window.scrollTo(0, 0); // reset in case prev not scrolled
var nPageH = $(document).height();
var nViewH = window.outerHeight;
if (nViewH > nPageH) {
nViewH = nViewH / window.devicePixelRatio;
$('BODY').css('height', nViewH + 'px');
}
window.scrollTo(0, 1);
} else {
addEventListener("load", function() {
setTimeout(hideURLbar, 0);
setTimeout(hideURLbar, 500);
}, false);
}
function hideURLbar() {
if (!pageYOffset) {
window.scrollTo(0, 1);
}
}
return this;
}
</script>
</head>
<body>
<section>
<div>
<h1>First title</h1>
<p>Just some content</p>
</div>
</section>
<section>
<div>Any text</div>
</section>
</body>
</html>
Of course you need to put the jQuery main js file as well in order this example work properly. You can download from here http://jquery.com/download/
try this
$(document).ready(function() {
if (navigator.userAgent.match(/Android/i)) {
window.scrollTo(0,0); // reset in case prev not scrolled
var nPageH = $(document).height();
var nViewH = window.outerHeight;
if (nViewH > nPageH) {
nViewH -= 250;
$('BODY').css('height',nViewH + 'px');
}
window.scrollTo(0,1);
}
});
it works even if your page is not long enough
Try this one. I've used it and it seems to work perfectly on Android. It's from here:
https://gist.github.com/1183357
/*
* Normalized hide address bar for iOS & Android
* (c) Scott Jehl, scottjehl.com
* MIT License
*/
(function( win ){
var doc = win.document;
// If there's a hash, or addEventListener is undefined, stop here
if( !location.hash && win.addEventListener ){
//scroll to 1
window.scrollTo( 0, 1 );
var scrollTop = 1,
getScrollTop = function(){
return win.pageYOffset || doc.compatMode === "CSS1Compat" && doc.documentElement.scrollTop || doc.body.scrollTop || 0;
},
//reset to 0 on bodyready, if needed
bodycheck = setInterval(function(){
if( doc.body ){
clearInterval( bodycheck );
scrollTop = getScrollTop();
win.scrollTo( 0, scrollTop === 1 ? 0 : 1 );
}
}, 15 );
win.addEventListener( "load", function(){
setTimeout(function(){
//at load, if user hasn't scrolled more than 20 or so...
if( getScrollTop() < 20 ){
//reset to hide addr bar at onload
win.scrollTo( 0, scrollTop === 1 ? 0 : 1 );
}
}, 0);
} );
}
})( this );

Different encoding issue

I'm writing an android app that implements a web server that sends pages containing text messages.
By client side I developed a web interface. This interface contains some DIVs that are filled using ajax and in particular with this functions that gets a page and put it into a specified div:
function getElementFromId(myElement) {
var elem;
if(document.getElementById)
elem = document.getElementById(myElement);
else
elem = document.all[myElement];
return elem;
}
function getXMLHttpRequest() {
var XHR = null, browser = navigator.userAgent.toUpperCase();
if(typeof(XMLHttpRequest) == "function" || typeof(XMLHttpRequest) == "object")
XHR = new XMLHttpRequest();
else if(window.ActiveXObject && browser.indexOf("MSIE 4") < 0) {
if(browser.indexOf("MSIE 5") < 0)
XHR = new ActiveXObject("Msxml2.XMLHTTP");
else
XHR = new ActiveXObject("Microsoft.XMLHTTP");
}
return XHR;
}
function pageInDiv(nomeFile,divId) {
var ajax = getXMLHttpRequest(), elem = getElementFromId(divId),
usaLink = true;
if(ajax) {
usaLink = false;
ajax.open("get", nomeFile, true);
//ajax.setRequestHeader("connection", "close");
ajax.onreadystatechange = function() {
if(ajax.readyState == 4) {
if(ajax.status == 200)
elem.innerHTML = ajax.responseText;
else
elem.innerHTML += "Error: " + statusText[ajax.status];
}
}
ajax.send(null);
}
return usaLink;
}
Now there's the problem! When I call pageInDiv("pageWithText.html",myDiv) the div is filled correctly, except for accented caracters. If the text contains àèìòù, the div will contain strange symbols, but (this is the strangest thing) if I open the page http://.../pageWithText.html directly in the browser it appears perfectly!
What's the problem? Thank you in advice
Update
This a piece of the web interface code:
<body onLoad=" pageInDiv('conversations.html', 'conversations');>
And this is the code of conversations.html:
<div id="conversations" class="list">
<div id="main">
<div id="msgTitle">Io</div>
<div id="message"><div id="img">
<img class="convimg" src="contactphoto_8259.jpg"></div>
<div id="text">������</div></div><div id="line"></div>
</div>
You should try to include the following code in the html page where you have these encoding problems
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
...
</head>
If this encoding it's not working (I doubt it) you can try with different code from this page.

Categories

Resources