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>');");
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
}
}
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.
I want to pass some values to the JavaScript function from the android Java code. The Java script function is written in a HTML file. And I am loading the HTML file in a web-view.
My main target is to update the JavaScript variable values, that are using to draw pie,bar and line chart.
Activity In android:
WebView mWebView = (WebView)findViewById(R.id.webviewId);
mWebView.loadUrl("file:///android_asset/bar.html");
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setSaveFormData(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.setWebViewClient(new MyWebViewClient());
}
My question is how can i pass data from android Java to Java Script which is inside a HTML file
Hmmmmm...something like that...
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
// Calling arg-less js method form android
webView.loadUrl("javascript:window.yourJsFunc();");
// I'm not sure with passing args, but you can try this...
webView.loadUrl("javascript:window.yourJsFunc(\"arg0\", \"arg1\");");
}
});
NOTE: In your case, if you implemented MyWebViewClient, you can override its onPageFinishied() and put this code in.
hope this helps..
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>
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.