In my app i need to pass some values to HTML page and i need to get values from HTML page
To get values i am following these steps
Create JavaScriptInterface class like
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", "value:" + passedValue);
}
}
Adding the interface to web view
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
Now in your HTML page, call the method to pass value
<input type="button" value="ClickMe" onClick="passValueToAndroid('Hello Android!')" />
<script type="text/javascript">
function valueToAndroid(value) {
Android.showMyValue(yourPassingValue);
}
</script>
In the same way i need to pass value from my activity to HTML content
I have a layout having linear layout with three buttons and web view. In WebWiew i use to load the HTML file which i have in assets folder. When i click the button in linear layout i need to hide some text within the HTML file.
I don't want to have separate HTML files for each button action how to do this
You can run arbitrary javascript on your WebView by calling webView.loadUrl("javascript:(function(){<your code here})()"); in the UI thread.
Related
let's say that i have google page loaded in webview, then i searched for something,
So the page changed, and there's a text in this page that i want to get it in my android app, in textView by using the code below
webview.loadUrl("javascript:api.getSessionID(document.querySelector(bla bla bla)");
class JSInterface {
#JavascriptInterface
public void getSessionID(String id) {
Toast.makeText(context,id, Toast.LENGTH_LONG).show();
}
How can i inject this js in the shown page in webview, not in the page that loaded first in webview which is google search page
Google just an example, i'm trying to save a session id in sharedPreferences when a user loggin in the account, which is the second page
Note: i have all the necessary codes in my full code in order to inject js and get string from it
Note2: if i reloaded the page, i will sign out
Appreciate any help !
your WebView first of all, we must tell the WebView to enable the JavaScript execution:
webview.getSettings().setJavaScriptEnabled(true);
Then we must set the WebViewClient in order to receive the onPageFinished event.
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPag`enter code here`eFinished(view, url);
webView.loadUrl(
"javascript:(function() { " +
"var element = document.getElementById('hplogo');"
+ "element.parentNode.removeChild(element);" +
"})()");
}
});
To acheive this you can evaluate javascript as,
webview.evaluateJavascript("Your JS here which will return session id",
html1 -> Log.i("HTML", html1));//session id will be printed
Also, make sure you have enabled java script to run in webview webView.getSettings().setJavaScriptEnabled(true);
EDIT
Second approach,
If you want to implement an interface which will give callback do change in your webpage as,
if (typeof YourListener != 'undefined')//check if yourlistner is undefined
yourListener.onTextChange('theReturnValue');
});
In above code the interface is called from webpage same as we do in android. Just apply JS at 'theReturnValue' here you need to retun required value from webpage.
And then add to webview that interface as,
webview.addJavascriptInterface(new WebAppInterface(getActivity(), webview), "YourListener");
also, add interface as,
public class WebAppInterface {
Context mContext;
WebView mView;
/**
* Instantiate the interface and set the context
*/
WebAppInterface(Context c, WebView w) {
mContext = c;
mView = w;
}
/**
* Show a toast from the web page
*/
#JavascriptInterface
public void onTextChange(String html) {
//you will get the callback text here
}
}
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.
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
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>
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>');");