Android - How to generate touch event from javascript?

邮差的信 提交于 2019-12-24 01:13:10

问题


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:


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


来源:https://stackoverflow.com/questions/12829598/android-how-to-generate-touch-event-from-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!