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.
Related
I have an android email client. When it receives message from an outlook2011 in mac, I get a html data like this:
<html><head></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space; color: rgb(0, 0, 0); font-size: 14px; font-family: Calibri, sans-serif; "><ol><li>One</li><li>Two</li><li>Three</li></ol></body></html>
And it shows the bullets properly.
However, When I receive similar message from Outlook2013 in Windows, I get this html data:
<html>
<head>
<style>
<!--
p.MsoNormal, li.MsoNormal, div.MsoNormal
{margin:0in;
margin-bottom:.0001pt;
font-size:11.0pt;
font-family:"Calibri","sans-serif"}
-->
</style>
</head>
<body lang="EN-US" link="#0563C1" vlink="#954F72">
<div class="WordSection1">
<p class="MsoListParagraph" style="text-indent:-.25in"><span style="">1.<span style="font:7.0pt "Times New Roman"">
</span></span>one</p>
<p class="MsoListParagraph" style="text-indent:-.25in"><span style="">2.<span style="font:7.0pt "Times New Roman"">
</span></span>two</p>
<p class="MsoListParagraph" style="text-indent:-.25in"><span style="">3.<span style="font:7.0pt "Times New Roman"">
</span></span>three</p>
</div>
</body>
</html>
And the webview in my app fails to render the bullets. It shows the text, but no bullets (numbered list).
The webview code is simple one.
private WebView mMessageContentView; //declaration
onCreate() {
mMessageContentView = whatever.getView(view, R.id.message_content);
//setup some zoom settings etc etc
mMessageContentView.setWebViewClient(someWebViewClientInstance);
}
private void setMessageHtml(String html) {
if (html == null) {
html = "";
}
if (mMessageContentView != null) {
mMessageContentView.loadDataWithBaseURL("email://", html, "text/html", "utf-8", null);
}
}
How can I fix this?
I added the following definition in style.css file in assets folder.
p.MsoNormal, li.MsoNormal, div.MsoNormal
{margin:0in;
margin-bottom:.0001pt;
font-size:12.0pt;
font-family:Cambria;}
p.MsoListParagraph, li.MsoListParagraph, div.MsoListParagraph
{margin-top:0in;
margin-right:0in;
margin-bottom:0in;
margin-left:.5in;
margin-bottom:.0001pt;
font-size:12.0pt;
font-family:Cambria;}
.MsoChpDefault
{font-family:Helvetica;}
Then the following code edit to add the external css file.
private void setMessageHtml(String html) {
if (html == null) {
html = "";
}
if (mMessageContentView != null) {
String htmlWithExternalCSS = addStyleDefinition(html);
mMessageContentView.loadDataWithBaseURL("email://", htmlWithExternalCSS, "text/html", "utf-8", null);
}
}
private String addStyleDefinition(String html) {
//insert at the end of <head> tag
String headTag = "<head>";
int index = html.indexOf(headTag);
StringBuffer buff = new StringBuffer(html);
buff.insert(index+headTag.length(), "<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/style.css\" />";);
return buff.toString();
}
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".
I recently updated the version of PhoneGap/Cordova I was using to the most recent. There is a page in my app that keeps throwing the following error every time it loads.
Uncaught Reference Error: google is not defined
I tried to use a sample webpage directly from the google developer's site to try and narrow down my options, and still got the same error when trying to load that page on my phone. (found here: https://developers.google.com/maps/documentation/javascript/examples/map-simple). I should note, when running this webpage from google as an .HTML file in Chrome on my desktop it worked fine.
I have also tried to use the solution found here: Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX
however the initialize method was never even called, which leads me to believe it's a problem with my script tag that I'm still missing.
As far as I can tell, I am using proper script calls in my HTML:
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?<KEY>&sensor=false"></script>
and the javascript code that is crashing is as follows:
origins[0] = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
The full code is here:
<!DOCTYPE HTML>
<html>
<head>
<title>MASH Locations</title>
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
<link rel="stylesheet" type="text/css" href="styles/layout.css" />
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=(myAppKey)&sensor=false"></script>
<script type="text/javascript" charset="utf-8" src="Util.js"></script>
<script type="text/javascript" charset="utf-8" src="QuickSort.js"></script>
<script type="text/javascript" charset="utf-8" src="Location.js"></script>
<script type="text/javascript">
var origins, destinations;
var BORDER_ROW = '<tr><td colspan="3" class="location-result-border"> </td></tr>';
var RESULT_FORMAT = '<tr><td id="result_{7}" class="location-result-row" onclick="onLocationResultClick(\'{0}\', \'{1}\', \'{2}\', \'{3}\', \'{4}\', \'http://cloud.intelligentbits.net/mash/images/{5}\', \'{6}\')">'
+ '<table class="{8}">'
+ '<tr><td class="location-result-distance" rowspan="3"><div>{9}</div>miles</td>'
+ '<td class="location-result-logo" rowspan="3"><img src="http://sqldb.intelligentbits.net/mash/images/{5}" alt="{0}" /></td>'
+ '<td class="location-result-name">{0}</td></tr>'
+ '<tr><td class="location-result-address">{10}</td></tr>'
+ '<tr><td class="location-result-city">{11}</td></tr></table></td></tr>';
function onLoad()
{
// Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);
}
// PhoneGap is ready
function onDeviceReady()
{
navigator.geolocation.getCurrentPosition(onPositionFound, onPositionError);
}
function onPositionFound(position)
{
// get the current location
origins = new Array();
origins[0] = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
document.getElementById('finding').innerText = 'Finding our locations...';
readFile('http://sqldb.intelligentbits.net/mash/locations.txt', onLocationsFound);
}
// onPositionError Callback receives a PositionError object
function onPositionError(error)
{
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
function onLocationsFound(text)
{
if (text == null || text.length == 0)
{
document.getElementById('finding').innerText = 'An error occurred.';
return;
}
// split the text into lines (one line per location)
var lines = text.split(/\r?\n/g);
if (lines.length == 0)
{
document.getElementById('finding').innerText = 'An error occurred.';
return;
}
// destinations
destinations = new Array();
var locIdx = 0;
// iterate over lines/locations
for (var i = 0; i < lines.length; ++i)
{
// split into fields
var loc = new Location();
var fields = lines[i].split(';');
for (var j = 0; j < fields.length; ++j)
{
// split fields into name and value
var tokens = fields[j].split('=');
if (tokens.length != 2) continue;
switch (tokens[0].toUpperCase())
{
case 'NAME':
loc.Name = tokens[1];
break;
case 'ADDRESS':
loc.StreetAddress = tokens[1];
break;
case 'CITY':
loc.City = tokens[1];
break;
case 'STATE':
loc.Region = tokens[1];
break;
case 'POSTAL':
loc.PostalCode = tokens[1];
break;
case 'PHONE':
loc.Phone = tokens[1];
break;
case 'HOURS':
loc.Hours = tokens[1];
break;
case 'LOGO':
loc.LogoFileName = tokens[1];
break;
case 'EMAIL':
loc.Email = tokens[1];
break;
}
}
// save the destination
destinations[locIdx++] = loc;
}
if (destinations.length == 0)
document.getElementById('finding').innerText = 'An error occurred.';
else
calculateDistances(origins, destinations);
}
function calculateDistances(orig, dest) {
// the passed-in destinations are arrays of Location objects; Google Maps wants strings
var destStrings = new Array();
for (var i = 0; i < dest.length; ++i)
destStrings[i] = dest[i].ToAddressString();
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: orig,
destinations: destStrings,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, onDistancesFound);
}
function onDistancesFound(response, status)
{
if (status != google.maps.DistanceMatrixStatus.OK)
{
alert('Error was: ' + status);
}
else
{
// get the place we'll store the list
var p = document.getElementById('finding');
var table = document.getElementById('location-results');
var orig = response.originAddresses;
var dest = response.destinationAddresses;
p.innerText = 'Tap a location for more options.';
// iterate over origins
for (var i = 0; i < orig.length; ++i) {
var results = response.rows[i].elements;
// iterate over destinations
for (var j = 0; j < results.length; ++j) {
// split the location into the amount and units
var distance = results[j].distance.text.Trim().split(' ');
// update the locations
destinations[j].DistanceFromUser = parseFloat(distance[0]);
destinations[j].DistanceUnits = distance[1];
destinations[j].TimeFromUser = results[j].duration.text;
}
}
// sort the distances
QuickSort(destinations, 'DistanceFromUser');
// print the results
var tablerows = '';
for (var i = 0; i < destinations.length; ++i) {
var loc = destinations[i];
tablerows += RESULT_FORMAT.Format(loc.Name, loc.Phone, loc.ToAddressString(), loc.ToTwoLineAddressString(),
loc.Hours, loc.LogoFileName, loc.Email, i, 'location-result-' + ((i + 1) % 2 == 0 ? 'even' : 'odd'),
loc.DistanceFromUser, loc.StreetAddress, loc.City);
}
tablerows += '<tr><td><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/></td></tr>';
// append the rows
table.innerHTML += tablerows;
}
}
function onLocationResultClick(name, phone, address, displayAddress, hours, imageUrl, email)
{
// save the name and address to local storage for the directions
window.localStorage.setItem('location-position', address);
window.localStorage.setItem('location-address', displayAddress);
window.localStorage.setItem('location-title', name);
window.localStorage.setItem('location-hours', hours);
window.localStorage.setItem('location-phone', phone);
window.localStorage.setItem('location-imageUrl', imageUrl);
window.localStorage.setItem('location-contact', email);
// call link
window.location = 'location.html';
}
</script>
</head>
<body onload="onLoad()">
<h1>
<a href="index.html" class="back">
<div>
<span></span>
</div> <span class="text">Back</span>
</a> Nearest Locations
</h1>
<div id="location-results-wrapper">
<h1 style="position: static; width: 94%;">
<a href="#" class="back">
<div>
<span></span>
</div> <span class="text">Back</span>
</a> #
</h1>
<table id="location-results">
<tr>
<td id="finding" style="vertical-align: top;">Finding your
location...</td>
<tr>
</table>
</div>
</body>
</html>
and the exact error log:
06-27 09:06:00.624: E/Web Console(15020): Uncaught ReferenceError: google is not defined at file:///android_asset/www/locations.html:41
Try these
Check your internet connection
Keep Map API script tag as a first script tag in your code.
i.e Before loading any other javascripts load map API.
Hope this helps.
I found my solution. When running the update command for PhoneGap, the cordova.js and config.xml files were not copied over into the my project. I'm not sure if this is intentional (I easily could have missed documentation on this somewhere), but it seemed unintuitive at the time. After manually copying these two files into my project, everything worked.
When u're using multiple HTML pages. use the google API javascript on the main page(index). the Ajax will not relaod the map when its refreshed.
If google map api is not defined then it too can cause the problem.
Since i missed out while getting the address from latitude and longitude.
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
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 );