Exist stringByEvaluatingJavaScriptFromString for Android

前端 未结 2 1592
清酒与你
清酒与你 2021-01-20 02:07

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

相关标签:
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();
        }
    
    0 讨论(0)
  • 2021-01-20 02:51

    You can use loadUrl instead,eg:

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

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

    0 讨论(0)
提交回复
热议问题