Exist stringByEvaluatingJavaScriptFromString for Android

女生的网名这么多〃 提交于 2019-12-20 02:39:09

问题


Exist stringByEvaluatingJavaScriptFromString method in Android like Iphone?. Not with a simple code like this javascript:wave(). But with a complex Java Script function. Thanks


回答1:


You can use loadUrl instead,eg:

webView.loadUrl("javascript:PerformSimpleCalculation()");

It's effect similar to stringByEvaluatingJavaScriptFromString.The API description is not clear.




回答2:


stringByEvaluatingJavaScriptFromString is a private method in Android API. But it is really useful.

You could retrive this API via Java reflection:

Method stringByEvaluatingJavaScriptFromString , sendMessageMethod;;
    Object webViewCore , browserFrame;
private boolean hasIntercepted = true;
    Object webViewObject = this;
    Class webViewClass = WebView.class;
    try {
        Field mp = webViewClass.getDeclaredField("mProvider");
        mp.setAccessible(true);
        webViewObject = mp.get(this);
        webViewClass = webViewObject.getClass();
        Field wc = webViewClass.getDeclaredField("mWebViewCore");
        wc.setAccessible(true);
        webViewCore = wc.get(webViewObject);
        if (webViewCore != null) {
            sendMessageMethod = webViewCore.getClass().getDeclaredMethod("sendMessage", Message.class);
            sendMessageMethod.setAccessible(true);

            Field bf= webViewCore.getClass().getDeclaredField("mBrowserFrame");
            bf.setAccessible(true);
            browserFrame = bf.get(webViewCore);
            stringByEvaluatingJavaScriptFromString = browserFrame.getClass().getDeclaredMethod("stringByEvaluatingJavaScriptFromString", String.class);
            stringByEvaluatingJavaScriptFromString.setAccessible(true);   

        }
        hasIntercepted = true;
    } catch (Throwable e) {
        hasIntercepted = false;
    }

Then to use this method:

Object argument =(Object) ((String)"window.hitTest("+event.getX()+ ","+event.getY()+")");
    try {
        Object _tagName = stringByEvaluatingJavaScriptFromString.invoke(browserFrame, argument);
        String tagName =(String)_tagName;
    } catch (Exception e) {
        e.printStackTrace();
    }


来源:https://stackoverflow.com/questions/6456994/exist-stringbyevaluatingjavascriptfromstring-for-android

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