android html code from webview - android

hello i'm using this example http://lexandera.com/2009/01/extracting-html-from-a-webview/ to get the HTML from a webview. But i need to use it in my superclass and i dont know how to do this. I just can see the html on a AlertDialog but i cant use it. How can I return it to my main class as String?
final Context myApp = this;
/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface
{
#SuppressWarnings("unused")
public void showHTML(String html)
{
new AlertDialog.Builder(myApp)
.setTitle("HTML")
.setMessage(html)
.setPositiveButton(android.R.string.ok, null)
.setCancelable(false)
.create()
.show();
}
}
final WebView browser = (WebView)findViewById(R.id.browser);
/* JavaScript must be enabled if you want it to work, obviously */
browser.getSettings().setJavaScriptEnabled(true);
/* Register a new JavaScript interface called HTMLOUT */
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
/* WebViewClient must be set BEFORE calling loadUrl! */
browser.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
/* This call inject JavaScript into the page which just finished loading. */
browser.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
});
/* load a web page */
browser.loadUrl("http://lexandera.com/files/jsexamples/gethtml.html");

Do the Followings :
Setting up WebView
First add JavaScriptInterface to webView as follows. Here "Android" will be used later to call functions in JavaScriptInterface later.
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JavaScriptInterface(this), "MyAndroid");
The JavaScriptInterface Class:
public class JavaScriptInterface {
Context mContext;
JavaScriptInterface(Context c) {
mContext = c;
}
}
HTML File:
<html>
<head>
<script type="text/javascript">
function getValue()
  {
var x=document.getElementById("content").innerHTML;
//  alert(x);
MyAndroid.receiveValueFromJs(x);
  }
</script>
</head>
<body>
<div id="content">
This is html content <hr/>
Other contents;
<input type="button" onclick="getValue()" value="Get Content" />
</div>
</body>
</html>
Calling Java Script Function
//this calls javascript function
webView.loadUrl("javascript:getValue()");
Adding Callback function in JavaScriptInterface for MyAndroid.receiveValueFromJs(val):
public void receiveValueFromJs(String str) {
Toast.makeText(mContext, "Received Value from JS: " + str,Toast.LENGTH_SHORT).show();
}
Here you have returned HTML in str variable.
You can see my blog : http://ganeshtiwaridotcomdotnp.blogspot.com/2011/10/calling-javascript-function-from.html
for details.
I found another solution : Is it possible to get the HTML code from WebView

Can't you just make a global variable, like
String globalHtml;
And then assign it in the showHTML method?
globalHtml = html;
You can delete the AlertDialog code if you don't need it.

Related

Javascript Interface Constructor is Calling but the interface method is not getting called in android webview

Here is the code i used..
webview.getSettings().setJavaScriptEnabled(true); // enable javascript
webview.addJavascriptInterface(new
WebViewJavaScriptInterface(this), "Android");
and Javascript Interface class is
public class WebViewJavaScriptInterface{
private Context context;
WebView webView;
/*
* Need a reference to the context in order to sent a post message
*/
public WebViewJavaScriptInterface(Context context){
this.context = context;
Log.d("Inside Interface","Hello Vinod Dirishala");
}
/*
* This method can be called from Android. #JavascriptInterface
* required after SDK version 17.
*/
#JavascriptInterface
public void sendDataToDevice(String usertype,String userid){
Log.d("Inside SendData2Device","Hello Vinod Dirishala");
}
}
The above WebViewInterface Constructor is calling but the javascript method sendDataToDevice methos is calling which is a javascript method defined in php script like
Android.sendDataToDevice(val1,val2);
I tried your source, it works well.
I think the problem might be in your environment.
my steps is;
1. write html at (app\src\main\assets\test.html)
<html>
<script>
function echoBack()
{
var txtVal1 = document.getElementById("val1").value;
var txtVal2 = document.getElementById("val2").value;
Android.sendDataToDevice(txtVal1, txtVal2);
}
</script>
<body style="padding:10px;">
<br/><br/><input type="text" name="val1" id="val1" style="padding:10px;">
<br/><br/>
<br/><br/><input type="text" name="val2" id="val2" style="padding:10px;">
<br/><br/>
<input type="button" value="Send to Android" onclick="echoBack()" style="padding:10px;">
</body>
</html>
2. write activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true); // enable javascript
webview.addJavascriptInterface(new
WebViewJavaScriptInterface(this), "Android");
webview.loadUrl("file:///android_asset/test.html");
setContentView(webview);
}
public class WebViewJavaScriptInterface{
private Context context;
WebView webView;
/*
* Need a reference to the context in order to sent a post message
*/
public WebViewJavaScriptInterface(Context context){
this.context = context;
Log.e("Inside Interface","Hello Vinod Dirishala");
}
/*
* This method can be called from Android. #JavascriptInterface
* required after SDK version 17.
*/
#JavascriptInterface
public void sendDataToDevice(String usertype,String userid){
Log.e("Inside SendData2Device","Hello Vinod Dirishala");
}
}
}
3. running log
08-27 16:04:14.436 22459-22459/com.test E/Inside Interface: Hello Vinod Dirishala
08-27 16:04:26.586 22459-22511/com.test E/Inside SendData2Device: Hello Vinod Dirishala

Android put text in html

I got a html file like this:
<body>
<h2>My html</h2>
<p> You could save #value per year.</p>
</body>
I load this page in android with a WebView
I got a stored value that I need to replace with #value , is this possible?
Update PagerAdapterClass where i need to use it :
#Override
public Object instantiateItem(ViewGroup container, final int position) {
WebView Content;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.view_pager_item, container,
false);
Content= (WebView) itemView.findViewById(R.id.iaps_url);
Content.loadUrl(myUrl.get(position));
((ViewPager) container).addView(itemView);
return itemView;
}
myUrl.get(position) reprezents the file location like "file:///android_asset/ScreenOne.html"
Yes.
First read the HTML from assets/raw to a String. And then use the replaceAll function of the string.
InputStream is = getAssets().open("webpage.html");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String page = new String(buffer);
page = page.replace("#value", "new string");
WebView webview = (WebView)this.findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadDataWithBaseURL("", page, "text/html", "UTF-8", "");
Hi You can use the Android JavaScript Bridge technique. Look at below steps.
Steps 1. For enabling the Java script in a web view by default the JavaScript is disabled. You can enable through the WebSettings attached to your webview then enable the javascript with setJavaScriptEnabled()
For example
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
Steps 2. Building java script code to the android code
To bind the javascript and android code, it call addJavascriptInterface().passing it a class instance to bind to your JavaScript and an interface name that your JavaScript can call to access the class.
For example, you can include the following class in your Android application:
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** call the stored value from java to javascript */
#JavascriptInterface
public integer getStoreValue() {
return 1;
}
}
You can bind this class to the JavaScript that runs in your WebView with addJavascriptInterface() and name the interface Android. For example:
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
This creates an interface called Android for JavaScript running in the WebView. At this point, your web application has access to the WebAppInterface class. For example, here's some HTML and JavaScript that call the java stored value using the new interface when html widnow load: #see this link
<html>
<script type="text/javascript">
function getStoredValue() {
var output = document.getElementById('values');
output.innerHTML = Android.getStoreValue();
}
</script>
<body onload="getStoredValue()">
<h2>My html</h2>
<p> You could save <a id= 'values'>
</a> per year.</p>
</body>
</html>
Let me know if you have any doubt, thank you.

Can I pass Particular Values from html page to My Activity?

I have one query. Can I pass Value from my html page to My Activity file.
html file located in assets/www folder and Activity file located in src/package_name
You need to use JavaScriptInterface. In your web view add this Interface.
Make JavaScriptInterface class like (Here you can use any name for your class)
public class JavaScriptInterface {
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface(Context context) {
mContext = context;
}
/** Get passed value from the web page here */
public void showMyValue(String passedValue) {
android.util.Log.i("TAG", "I Got this value:" + passedValue);
}
}
Add this interface in your webview like
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
Now in your webpage, call this method to pass your value and do something need full with that value
<input type="button" value="ClickMe" onClick="passValueToAndroid('Hello Android!')" />
<script type="text/javascript">
function passValueToAndroid(yourPassingValue) {
Android.showMyValue(yourPassingValue);
}
</script>
Yes you can pass any variable from html to activity.
You need to create JavaScript Interface to interact between html to activity,
Refer this link for implementation detail
http://developer.android.com/guide/webapps/webview.html

number of links in a webpage with webview

I have defined some webview and I open some webpage on it
WebView wv = (WebView) findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl("http://mypage.com/");
My question is how can I count the number of links in that webpage ?
my first idea was to parse the html code and to count the "href" string in that html, but this solution sound like a noob solution to me. Is there more intelligent way to do this ?
If you can edit the HTML I think you can do that with a simple javascript function that sends the count data back to Android. You can see an answer about that here
The function in Javascript to count links can be as simple as this:
<script type="text/javascript">
function countLinks()
{
var all_a = document.getElementsByTagName("a");
return all_a.length;
}
</script>
First declare a JavaScriptInterface in android code:
public class JavaScriptInterface {
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface(Context c) {
mContext = c;
}
/** Get number of links */
public void getNumOfLinks(int numOfLinks) {
// Use the count as you like
}
}
Then add this interface to your webview, when you call it:
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
Finally in the HTML code get the number of links from DOM and pass it to the java code via the interface:
<script type="text/javascript">
Android.getNumOfLinks(document.getElementsByTagName("a").length)
</script>

Read HTML content of webview widgets

I want to read HTML content of webview widgets.
Is there any property or method which can be used to fetch the HTML of the currently open page?
You can inject a javascript into webView and get the html element. Check below code...
class MyJavaScriptInterface {
#SuppressWarnings("unused")
#JavascriptInterface
public void showHTML(final String html) {
//HTML content of the page
}
}
mWebView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
mWebView.loadUrl("javascript:window.HTMLOUT.showHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");

Categories

Resources