Android Browser Issue with jQuery Ajax and when appcache is used - android

we are having a problem with the built in browser on Android 4.0, 4.1 and 4.2 (we haven't got anything lower to test on).
The problem is that the ajax call will work perfectly on first load, you can press the run Ajax button as many times as you like and it will be fine. You can disconnect from the internet and it will work properly.
But if you exit (FULLY, make sure its not just running in the background) the browser then relaunch it, it will fail on load and on button press. It doesn't matter if you are on-line or off-line.
The error that is been returned from the ajax call is "Error" with status = 0 and readyState = 0.
When its successful you get a message back says "respose from Ajax Call" with a status = 200 and a readyState = 4.
The code works find on every other browser we have tested on Android Chrome, Firefox and Opera. on IOS 5 and 6 it works and every desktop browser we can find.
Is there something that I missing or have we found a bug in the built in browser. Any help on this would be appreciate especially if it just something stupid I have done.
We have created a test script that demonstrates this problem well I have attached it to the bottom of this message.
Thanks
Tim
test.php
<?php
function displayPage() {
?>
<!DOCTYPE html>
<html manifest="test.manifest" debug="true">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" >
<title>test</title>
<script type="text/javascript" src="jquery-1.9.0.min.js"></script>
<script type="text/javascript">
function runAjaxGet() {
var XMLHttpRequest = $.ajax({
url: "test.php",
dataType: "json",
data: "test=test",
traditional: "true",
success: function( responseData ) {
alert('good\n responseData: '+responseData+ '\n res:' + XMLHttpRequest.responseText +'\n readyState: '+ XMLHttpRequest.readyState + '\n Status: '+XMLHttpRequest.status );
console.log(XMLHttpRequest);
},
error: function (xhr, ajaxOptions, thrownError, responseData) {
alert('bad\n responseData: '+responseData+ '\n res:' + XMLHttpRequest.responseText +'\n readyState: '+ XMLHttpRequest.readyState + '\n Status: '+XMLHttpRequest.status);
console.log(XMLHttpRequest);
}
});
}
$(document).ready(function() {
runAjaxGet();
});
</script>
</head>
<body>
<button Name="Run Ajax" onclick="runAjaxGet();">Run Ajax</button>
</body>
</html>
<?php
}
function processRequests() {
header("Content-Type: application/json; charset=UTF-8" );
echo (json_encode("respose from Ajax Call"));
}
date_default_timezone_set ( "UTC" );
if (isset($_REQUEST['test'])) {
$which = $_REQUEST['test'];
} else {
$which = '';
}
switch ($which) {
case "test":
processRequests();
break;
default :
displayPage();
break;
}
?>
test.manifest
CACHE MANIFEST
test.php
jquery-1.9.0.min.js
test.php?test=test

Just add NETWORK section with asterisk and it will work
CACHE MANIFEST
test.php
jquery-1.9.0.min.js
test.php?test=test
NETWORK:
*

I hit this same problem and determined that when retrieved from the cache, 0 indicates success. This is likely because there is no actual http request involved since the request is resolved entirely locally.
Appcache manifest file:
CACHE MANIFEST
CACHE:
/config
Javascript:
var request = new XMLHttpRequest();
request.open('GET', '/config', false); // async=false is ok because this file will always come from AppCache
request.send(null);
// Older versions of android return 0 when ajax request retrieved from appcache
if (request.status == 200 || request.status == 0) {
return JSON.parse(request.responseText);
} else {
console.log("ERROR: config not retrievable");
throw "Attempt to retrieve config return http status " + request.status;
}

Related

Android 13 - getCurrentPosition - simple HTML

this simple HTML code attached at the bottom, runs on Windows 11/Android 8 with no issues.
on Android 13, I am unable to run it.
I get -
ERROR(1): User denied Geolocation
the HTML file is located on the Galaxy S21 Internal storage and opened with Chrome.
I gave all permissions I know of, but no success.
I never got the prompt of "Allow access to your location".....
I am not an expert.
I would like to provide all the required permission in the HTML code itself, if possible.
thank you very much
<html>
<head>
<script type="text/javascript">
var x = document.getElementById("demo");
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
const crd = pos.coords;
alert(`${crd.latitude} ${crd.longitude}`);
}
function error(err) {
alert(`ERROR(${err.code}): ${err.message}`);
}
function getLocation() {
//alert("getLocation")
if (navigator.geolocation) {
//alert("getLocation true")
navigator.geolocation.getCurrentPosition(success, error, options);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
alert(position.coords.latitude + "," + position.coords.longitude)
}
</script>
</head>
<body>
<p>
Click on the button to find your location.
</p>
<button onclick="javascript: getLocation();">Get my location</button>
<div id="demo">
</div>
</body>
</html>

Websockets in WebViews failing to connect, returning code 1006

I have created a simple websocket in an HTML page that works great and connects fine in all of the web browsers. However, when I load it in a web view like in an Android App it fails to connect and returns the code 1006. It is trying to connect to a different URL/endpoint so I am thinking this might be a CORS issue. I am building for a minimum target of API 23.
<!DOCTYPE html>
<html>
<body>
<h1>Socket Connect</h1>
<div id="container"></div>
</body>
<script>
const div = document.getElementById('container');
try {
console.log('connect');
var ws = new WebSocket('wss://anotherserver.com:3000');
ws.binaryType = 'arraybuffer';
}
catch (err) {
}
ws.onerror = function (error) {
// error is always blank
console.log('error');
};
ws.onopen = function () {
div.textContent = 'Opened';
console.log('opened');
};
ws.onclose = function (error) {
// always = 1006
div.textContent = error.code;
console.log(error.code);
};
</script>
</html>
I have read a few other posts about setting some options in my code and I have done that. See here
myWebView.getSettings().setAppCacheEnabled(true);
myWebView.getSettings().setDatabaseEnabled(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.getSettings().setCacheMode(currentCacheMode); /* use cache if not expired */
myWebView.getSettings().setJavaScriptEnabled(true);
I have set cleartext in my manifest as well
It ended up being a CORS issue.

XDK built app not working

I searched a lot, but I couldn't find an answer. I use Intel XDK for Cordova/Phonegap development.
Everything is ok (emulate tabs, debug, etc.). I went to Build tab and get my .apk, moved it to SD card and installed, but, it doesn't work when run.
If I build my source with Phonegap Build (Online), everything works fine.
My JS code:
<script type="text/javascript">
document.addEventListener("backbutton", function(){ return; }, true);
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady()
{
//navigator.splashscreen.hide();
var server = 'http://xxxxxx/index.php?';
var user_uuid = device.uuid;
$( document ).ready
(
function()
{
$("#main_content").css("top", "50%");
$("#main_content").css("margin-top", "-"+($("#main_content").height()/2)+"px");
$("#main_content").show();
$("#big_img_load").attr("src", "img/ajax-loader.gif");
var xinv = setInterval
(
function()
{
var networkState = navigator.connection.type;
if(networkState.trim() == 'none')
$("#no_internet").show();
else
{
$.post
(
server+"do=boot",{useruuid: user_uuid},function(data)
{
if(data.trim() != "ok")
window.location = "error.html";
else
{
clearInterval(xinv);
window.location = "app.html";
}
}
);
}
},
1000
);
}
);
};
</script>
It remains in loading: No internet check, no POST to the URL, nothing.
Where is the problem? Why only build from XDK is not working?
My suspicion is you do not have the domain whitelisting section in the build settings set correctly for your app. See this article for some hints: https://software.intel.com/en-us/articles/cordova-cli-412-domain-whitelisting-with-intel-xdk-for-ajax-and-launching-external-apps and make sure to build your app using Crosswalk, not Android, for best results on Android devices.

PhoneGap Conversion - HTML to .apk

I am turning a HTML app into a .apk using https://build.phonegap.com and everything works great appart from my file selector.
<input name="file" type="file" id="file">
I want to be able to select images only (it doesnt matter if it can select more - but its the images I am looking for) from both camera and file system..
In the web version http://carbonyzed.co.uk/websites/assent/1/photos.html this works great from my phone, but when converted to .apk, this functionality is lost, and I can't seem to find anything on here, or online relating to this issue.
At least for me, the input file doesn't work in Phonegap.
You need use the Phonegap API to get picture and select the source where come from, like photolibrary, camera or savedphotoalbum.
See more info about camera.getPicture: http://docs.phonegap.com/en/2.1.0/cordova_camera_camera.md.html#camera.getPicture
and about Camera.PictureSourceType parameter of cameraOptions method: http://docs.phonegap.com/en/2.1.0/cordova_camera_camera.md.html#cameraOptions
Ended up using the Child Browser system like so
In the head
<script src="childbrowser.js"></script>
in the body
<button class="button-big" onClick="window.plugins.childBrowser.showWebPage('URL_TO_GO_HERE',
{ showAddress: false });" style="width: 100%;">UPLOAD PHOTOS</button>
which has a standard fileuploader like
<input name="file" type="file" id="file">
then it let me select from root storage, works in phonegap 2.2 onwards on both iOS and Android OS
To capture an image I used this in the head
<script type="text/javascript" charset="utf-8" src="json2.js"></script>
<script type="text/javascript" charset="utf-8">
// Called when capture operation is finished
//
function captureSuccess(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}
}
// Called if something bad happens.
//
function captureError(error) {
var msg = 'An error occurred during capture: ' + error.code;
navigator.notification.alert(msg, null, 'Uh oh!');
}
// A button will call this function
//
function captureImage() {
// Launch device camera application,
// allowing user to capture up to 2 images
navigator.device.capture.captureImage(captureSuccess, captureError, {limit: 2});
}
// Upload files to server
function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name;
ft.upload(path,
"http://my.domain.com/upload.php",
function(result) {
console.log('Upload success: ' + result.responseCode);
console.log(result.bytesSent + ' bytes sent');
},
function(error) {
console.log('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}
</script>
and this in the body
<input type="button" class="button-big" style="width: 100%;" onclick="captureImage();" value="TAKE PHOTO">
copy and past and it works a dream,
Check it out in this image
any questions, just email comment,
or email me... support#carbonyzed.co.uk

Webservice client to connect SugarCRM web service from PhoneGap

I have SugarCRM Web services in the below link.
http://www.sugarcrm.besplatform.com/soap.php?wsdl
Using web services, I wanted to login and list Leads Management Details through SugarCRM Web Services. I am not able to access SugarCRM web services because of "cross - domain security" issue and "same origin" issue.
I have tried using JSONP , but could not succeed.
I am new to jquery and jsonp. Some one could help me to solve this problem.
Thanks in advance.
using ajax code:
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
alert("inside ajax");
var username = "admin";
var password = "admin";
$.ajax({
url: "www.sugarcrm.besplatform.com/soap.php/login",
data: "{'user_name':'" + username + "','password':'" + password + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data == null) {
alert( "nothing.");
}
else {
alert(data);
}
},
error: function(e){
alert("failure : "+e);
}
});
using jsonp:
<script type="application/javascript" src="jquery-1.7.2.min.js"></script>
<script type="application/javascript">
var url = "http://www.sugarcrm.besplatform.com/soap.php/login?user_name=admin&password=admin";
jQuery.getJSON(url+"&callback=?", function(data) {
alert("Success" + data.id);
});
</script>
I think you need to send the password MD5 encrypted to Sugar. Also there's a REST WS available at "../service/v2/rest.php" that you could use instead of the SOAP interface.
Since version 6.5.11 this is fixed. If you use "jsoncallback" and then the name it works. Take a look at the file service/core/REST/SugarRestJSON.php to see what changed and patch older versions of sugar

Categories

Resources