number of links in a webpage with webview - android

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>

Related

local page in webview not showing

Using webView.loadUrl is working for https site , but not with my local page which is located in /Applications/MAMP/htdocs/test.html
webView.loadUrl("/Applications/MAMP/htdocs/test.html") is not working
webView.loadUrl("http://localhost:8080/test.html"); is not working
Below is the test.html file
<!DOCTYPE html>
<html>
<head>
<title>Sample Page</title>
</head>
<body>
<h2>JS alert Example</h2>
<button onclick="myFunction()" >Try it</button>
<script>
function myFunction (){
Android.showToast("Sample Android toast message");
}
</script>
</body>
</html>
Now I want to load this page using webView .
Below is the mainactivity.java code
public class MainActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
webView = (WebView) findViewById(R.id.webview);
webView.loadUrl("http://127.0.0.1:8080/test.html");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.addJavascriptInterface(new WebAppInterface (this), "Android");
}
}
Below is my WebInterface java class :
public class WebAppInterface {
private Context context;
public WebAppInterface (Context context){
this.context = context;
}
#JavascriptInterface
public void showToast (String message){
Toast.makeText(context,message,Toast.LENGTH_LONG).show();
}
}
Now ,I cant understand why it is not loading the web page mentioned in webView.loadUrl . Note: I having given internet permissions in manifest file.
So if the file is local in the device (android phone), you need to have the path of the file. If the file is bundled in the assets, you can open the file like:
webView.loadUrl("file:///android_asset/filename.html");
Or if you can't find it, you can put the file in the raw resources and read the file into a string and then use:
webView.loadData(htmlString, "text/html", "utf-8");
In any case, most probably the problem you have is you can't find the file. So make sure you are placing the file in the proper place in the assets, or resources. And you are accessing the file correctly.
Here is the documentation on how to access the resources:
https://developer.android.com/guide/topics/resources/providing-resources
If what you mean by local is on your computer, and you are hosting the file (which I assume would be just for testing), then you need to connect the android device / emulator to the same local network as your computer and then access via the local ip of your computer.
And here is another question similar to this that has already been answered:
Load HTML file into WebView

android passing values to HTML pages

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.

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

android html code from webview

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.

Categories

Resources