sofarsogood
sofarsogood

Reputation: 51

Android - How to generate touch event from javascript?

Is it possible to generate a touch event in javascript that'll invoke the onTouchEvent() function in my android WebView?

I tried with the following javascript code which generates both touchstart and touchend events, but my webview onTouchEvent() function does not get invoked.

try{
var evt = document.createEvent('TouchEvent');
evt.initTouchEvent('touchstart', true, true);
evt.view = window;
evt.altKey = false;
evt.ctrlKey = false;
evt.shiftKey = false;
evt.metaKey = false;
this.dispatchEvent(evt);

var evt1 = document.createEvent('TouchEvent');
evt1.initTouchEvent('touchend', true, true);
evt1.view = window;
evt1.altKey = false;
evt1.ctrlKey = false;
evt1.shiftKey = false;
evt1.metaKey = false;
this.dispatchEvent(evt1); 

}
catch(e)
{
    alert(e);
}

Is something missing from my code, or do the javascript events not even get into the android framework?

Thx

Upvotes: 2

Views: 2411

Answers (1)

Kirk B.
Kirk B.

Reputation: 456

Not sure how you plan to use the touch event, and also not sure you can bubble touch events from the rendered dom up to the containing webview control's handler, but you could try this approach:

1) Add a javascript interface to your web view and expose a simple object of a class that captures your dom-generated events:

(inside onCreate of ContainerActivity)

this.mWebView.addJavascriptInterface
    ( new JavascriptContainer() {
        final private WebView mView = ContainerActivity.this.mWebView;

        @Override
        public void captureEvent(final String sDetails) {
            // do what you want with the details and webview...
        }
    }
    , "appReceiver"
    );

2) Capture touch events or click event (or whatever) in your rendered html and use javascript to delegate them to the exposed global "appReceiver":

if (window.appReceiver !== undefined) {
    window.appReceiver.captureEvent('blah blah: ' + event.x + ':' + event.y);
    ...
}

Upvotes: 2

Related Questions