Android中存在stringByEvaluatingJavaScriptFromString

时间:2011-06-23 15:52:58

标签: javascript android inject

Android中存在stringByEvaluatingJavaScriptFromString方法,如Iphone? 不是像这样的简单代码javascript:wave()。但是具有复杂的Java Script功能。 感谢

2 个答案:

答案 0 :(得分:0)

您可以改为使用loadUrl,例如:

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

它的效果与stringByEvaluatingJavaScriptFromString类似.API说明不明确。

答案 1 :(得分:0)

stringByEvaluatingJavaScriptFromString是Android API中的私有方法。但这确实很有用。

您可以通过Java反射来检索此API:

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

然后使用此方法:

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