jQuery $.post() is not working in Android WebView - android

I am trying to call JavaScript from Android but $.post() is not working. I tried it in Postman and it is working.
o/p: output is not defined
MainActivity.java
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/newhtml.html");
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:loadjs()");
}
});
newhtml.html
<!Doctye HTML>
<html>
<head>
<title></title>
<script src="jquery.min.js"></script>
<script type="text/javascript">
function loadjs(){
console.log("called");
var json_config = {
name: "Donald Duck",
city: "Duckburg"
};
console.log("name "+json_config.name);
console.log("city "+json_config.city)
$.post("http://www.w3schools.com/jquery/demo_test_post.asp",json_config,function(data,status){
console.log("data "+data);
console.log("status "+status);
}).fail(function(response) {
console.log("output is "+response.responseText)
});
}
</script>
</head>
<Body>
<div id="print_host"></div>
</Body>
</html>

Related

html5 video play issue in android 4.2

I am creating an app with a WebView thats supposed to play a mp4 video using html5 "video" tag.
This is simple html5 code which is working fine in browser but not in android
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<video id="vd1" src="path/video.mp4" type="video/mp4" width="100%" height="100%" loop >
</video>
<script type="text/javascript">
var vid = document.getElementById("vd1");
if(vid){
vid.onloadeddata = function() {
vid.play();
alert("Browser has loaded the current frame");
}
}
/*
var video = document.getElementById('vd1');
if(video){
video.addEventListener('loadeddata', function() {
video.play();
});
}*/
</script>
</body>
</html>
But if i pass in pagefinished like below it is working fine.
webview.setWebViewClient(new WebViewClient() {
// autoplay when finished loading via javascript injection
public void onPageFinished(WebView view, String url) { mMessageContentView.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()"); }
});
so How can i use play event using this script tag in android webview?

Android WebView showing blank page for local files

My android WebView is showing a blank page when I try to load "file:///android_asset/index.html" and it perfectly loads other url like "http://twitter.com".
My activity
public class MainActivity extends ActionBarActivity {
private WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView = (WebView) findViewById(R.id.webview);
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("file:///android_asset/index.html");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.loadUrl("file:///android_asset/index.html");
return true;
}
return false;
}
}
My index.html file :
<!DOCTYPE html>
<html>
<head>
<title>World Tour</title>
<!-- Sets initial viewport load and disables zooming -->
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<!-- Makes your prototype chrome-less once bookmarked to your phone's home screen -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="mobile-web-app-capable" content="yes">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/ratchet.css">
</head>
<body>
<header class="bar bar-footer">
<span class="icon icon-info pull-left" ></span>
<span class="icon icon-plus pull-right" ></span>
<h1 class="title">List of previous drive</h1>
</header>
<div class="content">
<div class="card">
<ul id="drives-list" class="table-view">
<li class="table-view-divider table-view-cell" ><p class="pull-left">Comments</p><p class="pull-right">Distance</p></li>
</ul>
</div>
</div>
<script type="text/javascript" src="js/main.js" ></script>
<script type="text/javascript" src="js/ratchet.js" ></script>
</body>
</html>
Thanks for helping !
get string content from your assests file using below code
public static String getStringFromAssets(String name, Context p_context)
{
try
{
InputStream is = p_context.getAssets().open(name);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String bufferString = new String(buffer);
return bufferString;
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
and load content using below code
String m_data = getStringFromAssets("index.html", this);
webView.loadDataWithBaseURL("file:///android_asset/", m_data, "text/html", "utf-8", null);
Hope it works for you !!
Checkout if there are any errors in javascript code associated with the html page. If so android studio doesn't point out errors in js file.
I fixed the errors in the js file and it worked.

javascript callback in phonegap

An API call
<script type="text/javascript"
src="http://api.ipayy.com/v001/c/dc/getjsbykey?gh="xyz">
</script>
returns
window.onload = function() {
callback_fn.call(new Object(), false);
}
This works perfectly fine with browser.
But the same doesn't work with Phonegap, the callback function isn't executed in Javascript in Phonegap
<!DOCTYPE HTML>
<html>
<head>
<script src="cordova.js"></script>
<script>
function callback_fn() {
navigator.notification.alert("new func");
for (var i = 0; i < arguments.length; i++) {
alert(arguments[i]);
}
}
</script>
<script type="text/javascript" src="http://api.ipayy.com/v001/c/dc/getjsbykey?gh="+window.Encryption.encrypt()"></script>
</head>
<body>
</body>
</html>
Is there any equivalent of the following in Phonegap, which will call the function callback_fn()?
window.onload = function() {
callback_fn.call(new Object(), false);
}

html2canvas with phonegap error

Getting error
"11-13 13:10:55.470: E/Web Console(9799):
Uncaught Error: TYPE_MISMATCH_ERR: DOM Exception 17 at
file:///android_asset/www/index.html:304"
when converting html div content to canvas in android with phonegap.
It is working properly on browser. Any help will be appreciated. I am using jQuery-1.9.1, jQuery-UI.
code snippet:
// html file
<html>
<head>
<meta charset="utf-8" />
<title>jQuery UI Draggable - Default functionality</title>
<link rel="stylesheet" href="resourcess/css/jquery-ui.css" />
<script src="js/jquery-1.9.1.js"></script>
<script src="js/html2canvas.js"></script>
<script src="js/jquery.plugin.html2canvas.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/jquery.ui.touch-punch.min.js"></script>
<script src="cordova-2.5.0.js"></script>
<link rel="stylesheet" href="resourcess/css/style.css" />
</head>
<body>
<div class="imag-container">
<div class="dragImg">
<div id="dropHere"></div>
<div id="click" > click </div>
<div id="img-check">check</div>
<canvas id="canvas" width="100" height="100">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
</body>
// script
$(function(){
//Make every clone image unique.
var counts = [0];
var resizeOpts = {
handles: "all" ,autoHide:true
};
$(".dragImg").draggable({
helper: "clone",
//Create counter
start: function() { counts[0]++; }
});
$("#dropHere").droppable({
drop: function(e, ui){
if(ui.draggable.hasClass("dragImg")) {
$(this).append($(ui.helper).clone());
//Pointing to the dragImg class in dropHere and add new class.
$("#dropHere .dragImg").addClass("item-"+counts[0] );
$("#dropHere .img").addClass("imgSize-"+counts[0]);
//Remove the current class (ui-draggable and dragImg)
$("#dropHere .item-"+counts[0]).removeClass("dragImg ui-ggable ui-draggable-dragging");
$(".item-"+counts[0]).dblclick(function() {
$(this).remove();
});
make_draggable($(".item-"+counts[0]));
$(".imgSize-"+counts[0]).resizable(resizeOpts);
}
}
});
var zIndex = 0;
function make_draggable(elements)
{
elements.draggable({
containment:'parent',
start:function(e,ui){ ui.helper.css('z-index',++zIndex); },
stop:function(e,ui){
}
});
}
$('#click').click(function(){
//Some code
var domElement = document.getElementById('dropHere');
setTimeout(function() {
var canvas = document.getElementById("canvas"),
context = canvas.getContext('2d');
html2canvas(domElement, {
onrendered: function (domElementCanvas) {
var canvas = document.getElementById("canvas");
canvas.getContext('2d').drawImage(domElementCanvas, 0, 0, 50, 50,0,0,100,100);
}
});
}, 10000);
});
});

why javascript in webview does not work?

page loaded but javascript does not work!
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poll);
Device.webViewShowPoll = (WebView) findViewById(R.id.webViewShowPoll);
Device.webViewShowPoll.getSettings().setJavaScriptEnabled(true);
//Device.webViewShowPoll.getSettings().setPluginsEnabled(true);
Device.webViewShowPoll.getSettings().setJavaScriptEnabled(true);
Device.webViewShowPoll.getSettings().setPluginState(PluginState.ON);
Device.webViewShowPoll.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
Device.webViewShowPoll.getSettings().setAllowFileAccess(true);
Device.webViewShowPoll.addJavascriptInterface(appconnector, "appConnectr");
try
{
Device.webViewShowPoll.loadDataWithBaseURL("file:///android_asset/",
Utility.convertStreamToString(getAssets().open("index.htm",
AssetManager.ACCESS_BUFFER)), "text/html", "utf-8","");
}
catch (IOException e)
{
Log.e(getString(R.string.app_name), e.getMessage());
}
}
}
AND index.htm is :
<html>
<head>
<script type="text/javascript">
alert('Hello world!');
</script>
</head>
<body>
<p>Hello World!</p>
<p>Hello World!</p>
</body>
</html>
You haven't set a WebChromeClient to handle JS alerts
Device.webViewShowPoll.setWebChromeClient(new WebChromeClient());
JavaScript alert not working in Android WebView

Categories

Resources