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 );
Related
I'm trying to do 2 things at once with OnClick and don't know if I'm coding it wrong or if it's not possible. I'm trying to click on an image and using onclick go to another image while also playing a sound and then back to the original image. I have 3 examples in a row. The first example goes from image1 to image2 and back to image 1 without playing a sound. The 2nd example goes from image1 to image2 to image3 and back to image 1 without playing a sound. The third example plays a sound Onclick but its not going to image2. I want it to play a sound and also go to image2 when I click. Can anyone help?
http://readautism.atwebpages.com/index3.html
<!doctype html>
<html>
<head>
<meta charset="ISO-8859-1" />
<title>Example of How to Play a Sound on Click or on MouseOver</title>
<script>
var html5_audiotypes={ //define list of audio file extensions and their associated audio types. Add to it if your specified audio file isn't on this list:
"mp3": "audio/mpeg",
"mp4": "audio/mp4",
"ogg": "audio/ogg",
"wav": "audio/wav"
}
function createsoundbite(sound){
var html5audio=document.createElement('audio')
if (html5audio.canPlayType){ //check support for HTML5 audio
for (var i=0; i<arguments.length; i++){
var sourceel=document.createElement('source')
sourceel.setAttribute('src', arguments[i])
if (arguments[i].match(/\.(\w+)$/i))
sourceel.setAttribute('type', html5_audiotypes[RegExp.$1])
html5audio.appendChild(sourceel)
}
html5audio.load()
html5audio.playclip=function(){
html5audio.pause()
html5audio.currentTime=0
html5audio.play()
}
return html5audio
}
else{
return {playclip:function(){throw new Error("Your browser doesn't support HTML5 audio unfortunately")}}
}
}
//Initialize two sound clips with 1 fallback file each:
var mouseoversound=createsoundbite("whistle.ogg", "whistle.mp3")
var clicksound=createsoundbite('http://static.sfdict.com/staticrep/dictaudio/P05/P0501900.mp3', "whistle.ogg")
var uniquevar=createsoundbite("pizza.wav", "whistle.ogg", "whistle.mp3")
</script>
<script>
var gStorage = {};
function toogle(anImage, anAltSrcArr) {
if (typeof(anImage) === "undefined" || typeof(anAltSrcArr) === "undefined" || anAltSrcArr.length === 0) {
return;
}
var id = anImage.id;
var oldSrc = anImage.src;
if (typeof(gStorage[id]) === "undefined") {
gStorage[id] = {
'id': id,
'origSrc': oldSrc,
'i': 0
};
}
gStorage[id].i += 1;
if (gStorage[id].i > anAltSrcArr.length) {
gStorage[id].i = 0;
}
if (gStorage[id].i === 0) {
anImage.src = gStorage[id].origSrc;
} else {
anImage.src = anAltSrcArr[gStorage[id].i - 1];
}
}
</script>
</head>
<body
<p>Click on an image</p>
<img class="with-action" id="image1" name="image1" src="http://dummyimage.com/50/f00/fff&text=a" onclick='toogle(this, ["http://dummyimage.com/50/ab0/fff&text=b"]);' />
<img class="with-action" id="image2" name="image2" src="http://dummyimage.com/50/0f0/fff&text=a" onclick='toogle(this, ["http://dummyimage.com/50/0fa/fff&text=b", "http://dummyimage.com/50/0bb/fff&text=c"]);'/>
<img class="with-action" id="image3" name="image3" src="http://dummyimage.com/50/00f/fff&text=a" onclick="uniquevar.playclip()";'toogle(this, ["http://dummyimage.com/50/ab0/fff&text=b"])'; />
</body>
</html>
Try
<img class="with-action" id="image3" name="image3" src="http://dummyimage.com/50/0bb/fff&text=c" onclick="uniquevar.playclip();toogle(this, ['http://dummyimage.com/50/0fa/fff&text=b', 'http://dummyimage.com/50/0bb/fff&text=c']);">
Single and double quotes mix-up, apparent due to syntax-highlighting in the snippet that you posted.
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
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
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.