humkins
humkins

Reputation: 10705

Android. onReceiveValue method is not called after WebView.evaluateJavascript execution

I've created a new project based on Login Form template with Android Studio 1.5.1 and modified it little for my needs.

Here is build.gradle content

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"
    defaultConfig {
    applicationId "com.mia.jsrun"
    minSdkVersion 19
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
    }
    buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'com.android.support:design:23.2.0'
}

allprojects {
    buildDir = "/tmp/${rootProject.name}/${project.name}"
}

and here is my test code

private void test() {
    Log.d(TAG, "inside test()"); // is printed
    WebView webview = new WebView(this);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.evaluateJavascript("(function(){console.log('hello');return 'hello2'})()", new ValueCallback<String>() {
        @Override
        public void onReceiveValue(String s) {
            Log.e(TAG, "value received: " + s); // this is NOT printed
        }
    });
    Log.e(TAG, "after evaluateJavascript execution"); // is printed
}

Though I can see that evaluateJavascript method is invoked (logger prints before and after its execution) onReceiveValue is not.

What is wrong with my code or configuration?

Upvotes: 2

Views: 2248

Answers (1)

humkins
humkins

Reputation: 10705

Answering myself.

It was enough just to call webview.loadUrl(""); before evaluateJavascript() method invokation.

private void test() {
    WebView webview = new WebView(this);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.loadUrl("");
    webview.evaluateJavascript("(function(){return {foo:"bar"}})()", new ValueCallback<String>() {
        @Override
        public void onReceiveValue(String s) {
            Log.e(TAG, s); // {foo:"bar"}
        }
    });
}

Upvotes: 5

Related Questions