How does evaluateJavascript work?

后端 未结 6 831
执念已碎
执念已碎 2020-11-27 03:06

I\'m trying to use the new evaluateJavascript method in Android 4.4, but all I ever get back is a null result:

webView1.evaluateJavascript(\"return \\\"test\         


        
6条回答
  •  轮回少年
    2020-11-27 03:26

    OK, so it turns out the result here is the result of the Javascript call - as if one were entering the command into a Javascript console.

    So in order to get a result, it needs to be wrapped in a function:

    webView1.evaluateJavascript("(function() { return \"this\"; })();", new ValueCallback() {
        @Override
        public void onReceiveValue(String s) {
            Log.d("LogName", s); // Prints 'this'
        }
    });
    

    This will also work:

    webView1.evaluateJavascript("window.variable = \"asd\";", new ValueCallback() {
        @Override
        public void onReceiveValue(String s) {
            Log.d("LogName", s); // Prints asd
        }
    });
    

    The method also handles Javascript objects:

    webView1.evaluateJavascript("(function() { return { var1: \"variable1\", var2: \"variable2\" }; })();", new ValueCallback() {
        @Override
        public void onReceiveValue(String s) {
            Log.d("LogName", s); // Prints: {"var1":"variable1","var2":"variable2"}
        }
    });
    

提交回复
热议问题