2

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

1 Answer 1

2

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);
    ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

I can confirm this will work, I was going to answer the same. @sofarsogood on your WebView you add whatever object you want to have access on the JavaScript side using myWebView.addJavascriptInterface(aJavaObjectIWillUseInJavaScript,"myJavaObject"); Then on JavaScript, register an event listener that will use myJavaObject.someMethod(param1,param2,...) to trigger the desired behavior in Android-land.
I should also note the security issue this approach incurs... Any javascript rendered in your webview can call your exposed global captureEvent() method -- make sure to validate the passed-in arguments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.