首页 > 解决方案 > JavaScript onclick works in browsers, not in Android WebView

问题描述

I have a simple web application, which I'm trying to display through an Android WebView. The webpage consist of not much more than just one HTML table. Each of the cells of said table have an onclick property set to a javascript function, which brings up a box with some information.

This works well in all browsers, both desktop and mobile. However, when I try to click any of the table cells through my Android WebView, nothing happens, the webpage doesn't seem to recognise the clicks.

(Note: I did enable JavaScript for the webview, it does exactly what it should, for example when the document is loaded, only it doesn't recognise the clicks and doesn't fire the corresponding events.)

I've tried searching for an answer, but I had no luck. All threads I found were about solving different problems.

I'm not trying to run Android code by calling a JavaScript function, I only need the website JS to recognize the clicks.

What do I have to do to make this work? Thank you very much in advance, and please don't get too upset if my terminology isn't spot on, I'm just a self-taught enthusiast.

标签: javascriptandroidwebwebviewonclick

解决方案


原来问题是我setOnTouchListener用来处理 WebView 点击,即使我确保返回 false 以让 Android 知道点击应该由 WebView 进一步处理,但这并没有发生。我相信这可以通过在代码中的super.OnTouchEvent(event) 某个地方调用来解决,但我不确定我会如何做到这一点,而且我发现了一种非常简单的方法,在我看来它可以更清楚地了解实际发生的情况。

WebView这个想法是通过扩展和覆盖该onTouchEvent方法来创建一个自定义的“MyWebView”类:

public class MyWebView extends WebView
{
    private GestureDetector mDetector;

    public MyWebView(Context context)
    {
        super(context);
        mDetector = new GestureDetector(context, new MyGestureListener());
    }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        mDetector.onTouchEvent(event);
        this.performClick();
        return super.onTouchEvent(event);
    }

    @Override
    public boolean performClick()
    {
        return super.performClick();
    }

    class MyGestureListener extends GestureDetector.SimpleOnGestureListener
    {
        @Override public boolean onDown(MotionEvent event)
        {
            return true;
        }

        @Override public boolean onSingleTapConfirmed(MotionEvent e)
        {
            //do stuff here
            return false;
        }
    }
}

推荐阅读