JavaScript in a WebView - android

I have a block of html that has javascript embedded in it:
<!DOCTYPE html>
<html>
<body>
<h1>Testing</h1>
<script type="text/javascript">
var paEmbedId = 461745;
var paEmbedWidth = 600;
var paEmbedOemId = 24500;
var paServer = 'http://www.ncataggies.com/';
var paIframe = true;
</script>
<script type="text/javascript" src="http://www.ncataggies.com/oemjs/0/PhotoAlbum2009Embed.js"></script>
</body>
</html>
When I put the code inside a text document and run it from a browser(as a HTML file), the code runs perfectly.
How can I do this using a WebView in android?

You can use loadData method of WebView widget:
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webview.loadData(summary, "text/html", null);
// ... although note that there are restrictions on what this HTML can do.
// See the JavaDocs for loadData() and loadDataWithBaseURL() for more info.
If JS is not enabled, then you can also enable JS in WebView:
webview.getSettings().setJavaScriptEnabled(true);
But before that, you may want to read this from Android:
By default, a WebView provides no browser-like widgets, does not
enable JavaScript and web page errors are ignored. If your goal is
only to display some HTML as a part of your UI, this is probably fine;
the user won't need to interact with the web page beyond reading it,
and the web page won't need to interact with the user. If you actually
want a full-blown web browser, then you probably want to invoke the
Browser application with a URL Intent rather than show it with a
WebView.

Related

How to display image from javascript in Android web view

I want to display content from remote URL in android web view, which will be return by java script tag. In my case , java script tag return image , which should be load into web view.
Here is code to render image/content from remote URL.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
String customHtml = "<script src='http://mytestdomain.com/test.php?w=300&h=250' type='text/javascript'></script>" ;
webView.loadData(customHtml, "text/html", "UTF-8");
}
URL load the content but image are broken and do not display properly. Though i can click on on the image and land into correct link.
I have proper permission
<uses-permission android:name="android.permission.INTERNET"/>
How can i fix it. Any help is appreciate.
I think the issue is with your js code. I tried this code and image is showing fine.
<html>
<body>
<h3>A demonstration of how to access an IMG element</h3>
<img id="myImg" src="http://via.placeholder.com/350x150" alt="The Pulpit Rock" width="304" height="228">
<p>Click the button to get the URL of the image.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myImg").src;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
Also enable DomStorage:
webView.getSettings().setDomStorageEnabled(true);
Broken image issue because presence of protocol-relative url (//) for the image returned by our server. These kind of URLs (//:mytestdomain.com) will force the protocol to be the same as it's parent page, and the app's web view might be missing a base scheme for the image to inherit. I placed proper protocol into url and it working fine now

load a remote url with android webview and local css/js

For days...I try to find a solution to load a remote url with android webview. But with local css/js/images
But I couldn't.
I think it is impossible because of security issue... right?
I think mybe I could use a trick.
in remote server I just publish my webpage without <head> and <body>:
//<html>
// <head></head>
// <body>
... body code111 ... // there is only this part in remote url page
//</body>
//</html>
and then I create a index.html in android_asset folder:
<html>
<head>
<link css ...
<link java ...
</head>
<body>
... now put code111 here!
</body>
</html>
So now I can use local resource (in head)
I am new in android and java...I couldn't test it...but do you think is it possible?
well, let's start.
The easyer part is part B.
here you can find the answer:
Rendering HTML in a WebView with custom CSS
basically, what you have to do is have the html website on a String variable, ex:
String website = "<html><head>" + "<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />" + <"javascript call to file that i don't remember right now"/>" + "</head>"
and then append to that website, your remote HTML code. you could do it via, for example, any of the Async HTTP libraries ( LoopJ's one is quite good loopj's http library ) .
and then append the rest of your website.
website += retrieved_website
website += "</body></html>"
finally load the website using the .loadDataWithBaseURL() method as explained in the accepted respose.
althought i have to say this is quite a complicated way of loading a website, this would be my approach.

How can JSON be passed to AngularJS in Android webview?

I am trying to use an Android Webview to display some "active" content (sets of images that vary depending on some input settings). The content will be local (offline).
I would like to use Angular.js to control the media that will be displayed on the page.
So, to the problem... how can my Angular app receive JSON data on startup? The problem that I see is that the webview does not allow angular to lazy load additional files (I already ran into this while trying to use html templates for a custom directive. This required enclosing the HTML templates into the single HTML file).
My Android activity can write out the options somewhere, but how is Angular going to be able to read them? In other words, is there a way around the security settings of the webview which does not allow Angular.js to lazy load additional files?
I think that I've figured this one out. I realized that I can create a method in my Android Java code that is exposed to JavaScript (via #JavascriptInterface). This would allow me to call this method from my AngularJS app to get the JSON in a string (see this link for info on JavascriptInterface: http://developer.android.com/guide/webapps/webview.html). I'll post some code once I've proven that this works.
Here is the code. It works great.
MainActivity.java
public class MainActivity extends Activity {
private String MY_JSON_EXAMPLE = "{\"name\":\"John Doe\",\"email\":\"jdoe#testco.com\"}";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wv = (WebView) findViewById(R.id.myWebView);
wv.getSettings().setJavaScriptEnabled(true);
wv.addJavascriptInterface(this, "AndroidMainAct");
wv.loadUrl("file:///android_asset/mypage.html");
}
#JavascriptInterface
public String getMyJSONData() {
return MY_JSON_EXAMPLE;
}
}
mypage.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Hello World, AngularJS</title>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<h3>Load Test</h3>
<div ng-controller="MyController">
<div id="dataWaiting" ng-show="!myData.length">
Loading JSON...
</div>
<div id="dataLoaded" ng-show="myData.length">
Data Loaded: {{myData}}
</div>
</div>
</body>
</html>
app.js
var myApp=angular.module('myApp',[]);
myApp.controller('MyController', ['$scope', function($scope) {
$scope.myData = '';
this.loadData = function() {
// get the data from android
return AndroidMainAct.getMyJSONData();
};
$scope.myData = this.loadData(); // load data on instantiation
}]);
Exposing the data through the android JavascriptInterface method works great.

String from android activity to string in html inside assets folder

I Have an application with an html file inside of the assets folder. I want it so that when the user clicks a button, inside of the Android applications activity, the contents of the button get put into a string and passes the string to a string inside of the html file. Taking the contents of the button and passing them to a string inside of the activity I can do. I want to know how can I take the string, that I got from the button, and pass the information to the html file inside of my assets folder?
Are you just trying to display the HTML file with different data based on a button push? You can use %s or %d in your HTML file as well as $1..$n to do multiple replacements:
You have $1%d new $2%s.
Pseudo-Code
getHtmlFromAssets(myfile.html, unReadThings, things) where unReadThings is a number and things is a string.
Make sense?
Conceptually (though you'll be using HTML): http://mobile.tutsplus.com/tutorials/android/android-sdk-format-strings/
Or less Android specific: http://javarevisited.blogspot.com/2011/12/java-string-replace-example-tutorial.html
Resources (including Assets) are meant to be read. You can open a raw file, call a anim file, get a string from String xml file. However, you can't write to a resource.
As AssetsManager documentation states:
This class presents a lower-level API that allows you to open and read raw files that have been bundled with the application as a simple stream of bytes.
Now, what to do? I suggest you look into other types of Storage Options. For your case, I strongly suggest Using the Internal Storage.
addJavaScriptInterface method helps us pass values from a webpage to your android XML view or vice-versa. You can invoke your activity class method form your webpage
On create:
WebView Wv = (WebView) findViewById(R.id.webView);
Wv.getSettings().setJavaScriptEnabled(true);
JavaScriptInterface myJavaScriptInterface
= new JavaScriptInterface(this);
Wv.getSettings().setJavaScriptEnabled(true);
Wv.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
Wv.loadUrl("file:///android_asset/index.html");
then create a class myJavaScriptInterface
class JavaScriptInterface {
Context mContext;
int tpressure;
JavaScriptInterface(Context c) {
mContext = c;
tpressure=0;
}
public int Pressure(){
return tpressure++;
}
}
Sample html file would be:
<head>
<title>jQuery Mobile page</title>
<script src="jquery-1.9.1.min.js"></script>
<script src="jquery.mobile-1.3.2.min.js"></script>
<link rel="stylesheet" type="text/css" href="jquery.mobile-1.3.2.css" />
<script type="text/javascript">
$(document).ready(function () {
setInterval(function() {
$("#tire1").html(AndroidFunction.Pressure())
}, 2000);
});
</script>
</head>
<body>
<div id="some">
Tire Pressure:
</div>
<div id="tire1">
0
</div>
</body>

Problem with using FusionCharts for Android

I wanted to use FusionCharts with android 2.2 (may be on emulator).
I tried using Javascript and the HTML but did not get the expected result.
Any help??
My code is as follows :
WebView web;
/** Called when the activity is first created. */
#Override
public void on Create(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
web=(WebView)findViewById(R.id.webView1);
web.loadUrl("file:///android_asset/Fusioncharts/myChart.html");
}
}
Also my html,xml files :
<html>
<head>
<title>My First chart using FusionCharts
</title>
<script type="text/javascript" src="JavaScripts/FusionCharts.js">
</script>
</head>
<body>
<div id="chartContainer">FusionCharts will load here!
</div>
<script type="text/javascript">
<!--
var myChart = new FusionCharts("Pie2D.swf? dataURL=Data.xml","myChartId", "400", "300", "0", "1" );
myChart.setXMLUrl("Data.xml");
myChart.render("chartContainer");
// -->
</script>
</body>
</html>
and Data.xml :
The above code just displays me : FusionCharts will load here!
Thanks
Sneha
EDIT> NEW CONTENT:
You might need to enable JavaScript and plugins for the WebView:
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setPluginsEnabled(true);
http://developer.android.com/reference/android/webkit/WebView.html
What does "install Flash plugin" in WebView mean?
How to Enable Flash Plugin in Webview?
Also you might need to set proper path to the SWF and JS files. Please debug or attach code here.
OLD CONTENT:
There seems to be a JavaScript error or FusionCharts not getting loaded to do the rendering as stated by Duniyadnd.
Please check the Android debug (using adb logcat or other processes) if it traces any error.
Moreover, I did an implementation using PhoneGap which you can check-out from:
PhoneGap API to query call-logs
This is a small PhoneGap Android application which has FusionCharts to show call logs from the device. The post though showcases creation of plugin to get the calllog, you might derive the other elements which you require. Hope this might help.

Categories

Resources