AndroMeDev A Android Development Blog by Pim van Oers

24Mar/114

How to retrieve the contentWidth of a WebView

The extensive Android SDK allows you to do many great things with particular views like the WebView for displaying webpages on Android powered devices.
As of lately while I was experimenting with the Android SDK I was using a WebView in one of my activities.

From that particular WebView I needed to know the ContentHeight but also the ContentWidth. Now getting the contentHeight is easy like so:

webview.getContentHeight();

Unfortunately getting the contentWidth from a WebView is rather more difficult, since there is not a simple method like:

// THIS METHOD DOES NOT EXIST!
webview.getContentWidth();

There are ways to get the contentWidth of the rendered HTML page and that is through Javascript. If Javascript can get it for you, then you can also have them in your Java code within your Android App.

By using a JavascriptInterface with your WebView you can let Javascript communicate with your Android App Java code by invoking methods on a registered object that you can embed using the JavascriptInterface.

So how does this work?

For a quick example I created a simple Activity displaying a webview that loads a webpage wich displays a log message and a Toast message with the contentWidth wich was determined using Javascript. Note that this happens AFTER the page was finished loading, because before the page is finished loading the width might not be fully rendered. Also keep in mind that if there is content loaded asynchronously that it doesn't affect widths (most likely only heights will be affected as the width is almost always fully declared in CSS files unless you have a 100% width webpage).

Below is the code of the Activity Main.java:

package com.pimmos.android.samples.webviewcontentwidth;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class Main extends Activity {

	private final static String LOG_TAG = "WebViewContentWidth";
	private final Activity activity = this;

	private static int webviewContentWidth = 0;
	private static WebView webview;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);

		webview = (WebView) findViewById(R.id.webview);
		webview.getSettings().setJavaScriptEnabled(true);
		webview.setSaveEnabled(true);
		webview.addJavascriptInterface(new JavaScriptInterface(), "HTMLOUT");
		webview.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageFinished(WebView view, String url) {
				webview.loadUrl("javascript:window.HTMLOUT.getContentWidth(document.getElementsByTagName('html')[0].scrollWidth);");
			}
		});
		webview.loadUrl("http://www.pimmos.com/");
	}

	class JavaScriptInterface {
		public void getContentWidth(String value) {
			if (value != null) {
				webviewContentWidth = Integer.parseInt(value);
				Log.d(LOG_TAG, "Result from javascript: " + webviewContentWidth);
				Toast.makeText(
						activity,
						"ContentWidth of webpage is: " + webviewContentWidth
								+ "px", Toast.LENGTH_SHORT).show();
			}
		}
	}

}

Below is the XML layout used with the Activity wich only contains a simple WebView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<WebView android:id="@+id/webview" android:layout_width="fill_parent"
		android:layout_height="fill_parent" />
</LinearLayout>

AndroidManifest.xml layout:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.pimmos.android.samples.webviewcontentwidth"
	android:versionCode="1" android:versionName="1.0">
	<application android:icon="@drawable/icon" android:label="@string/app_name">
		<activity android:name=".Main" android:label="@string/app_name">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>

	</application>
	<uses-sdk android:minSdkVersion="7" />
	<uses-permission android:name="android.permission.INTERNET" />

</manifest>

You can also download the full source of Android Application - WebViewContentWidth!

 

Posted by Pimmos

Comments (4) Trackbacks (0)
  1. I wanted to jot down a quick note so as to say thanks to you for those fantastic steps you are posting at this site. My long internet investigation has finally been recognized with sensible facts to talk about with my family and friends. I would repeat that many of us site visitors are rather lucky to dwell in a really good place with many outstanding professionals with interesting pointers. I feel somewhat happy to have come across your webpage and look forward to plenty of more pleasurable times reading here. Thanks once again for everything.

    • I’m glad I could help you with this article. I was searching around for it as well, but there was no solution posted anywhere, so I started to write an article about it to share it. Anyways thanks for your kind words I will add new articles if I find more interesting things to write about.

  2. much thanx man.. good, nice and easy way.

  3. Hi Pimmos,
    I think there’s some easyer ways to get the content width, you can use capturePicture().getWidth() to get the width indirectly, or you can use the following method although it’s deprecated, hope can help you.
    webview.setPictureListener(new PictureListener() {

    @Override
    public void onNewPicture(WebView view, Picture picture) {
    // TODO Auto-generated method stub
    if (picture != null){
    width = picture.getWidth() ;
    setPictureListener(null);
    }
    }

    });


Leave a comment


- seven = 2

No trackbacks yet.

Switch to our mobile site