简体   繁体   中英

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.

Try it

在此处输入图片说明

Then in the HTML, call it directly from the button tag:

在此处输入图片说明

Turns out the problem was that I was using setOnTouchListener to handle the WebView clicks and even though I made sure to return false in order to let Android know that the click should be handled further by the WebView, that didn't happen. I believe that could be fixed by calling super.OnTouchEvent(event) somewhere in the code, but I'm not sure how exactly I'd do that and also I found quite a simple approach that in my opinion makes it way clearer what's actually happening.

The idea is to create a custom "MyWebView" class by extending WebView and override the onTouchEvent method:

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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM