WebViewでjavascriptを実行する


add this line to AndroidMAnifest.xml

```AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
```

```assets/form.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <form name="input" action="form.html" method="get">
        Enter Email: <input type="text" id="emailAddress"/>
        <input type="submit" value="Submit"/>
    </form>
</html>
```

add this line

```build.gradle
android {
    sourceSets{
        main{
            assets.srcDirs = ['assets']
        }
    }
}
```

![スクリーンショット 2016-08-08 23.31.19.png](https://qiita-image-store.s3.amazonaws.com/0/39073/0dae84f3-f8d5-8e11-fb74-eef3f237cc7b.png "スクリーンショット 2016-08-08 23.31.19.png")

When the view is created, we call the WebView.addJavascriptInterface() method to attach this object to the view and give it the name BRIDGE.

```
webview.addJavascriptInterface(new MyJavaScriptInterface(), "BRIDGE");
```


shouldOverrideUrlLoading is called before page is loading.
onPageFinished() is called when he page finishes loading.

javascript1の中身
javascript:window.BRIDGE.storeElement('emailAddress',document.getElementById('emailAddress').value)

Preferencesにデータを保存

```MyJavaScriptInterface
SharedPreferences.Editor edit = getPreferences(Activity.MODE_PRIVATE).edit();
            edit.putString(id, element);
            edit.commit();
```

javascript2の中身
javascript:document.getElementById('emailAddress').value='testeee'

Preferencesからデータを取得

```
SharedPreferences prefs = getPreferences(Activity.MODE_PRIVATE);
```


```MainActivity.java
package com.example.xxxxx;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WebView webview = new WebView(this);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setWebViewClient(mClient);
        webview.addJavascriptInterface(new MyJavaScriptInterface(), "BRIDGE");

        setContentView(webview);
        webview.loadUrl("file:///android_asset/form.html");
    }

    private static final String JS_SETELEMENT =
            "javascript:document.getElementById('%s').value='%s'";
    private static final String JS_GETELEMENT =
            "javascript:window.BRIDGE" +
                    ".storeElement('%s',document.getElementById('%s').value)";
    private static final String ELEMENTID = "emailAddress";


    private WebViewClient mClient = new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.v("javascript1", String.format(JS_GETELEMENT, ELEMENTID, ELEMENTID));
            executeJavascript(view, String.format(JS_GETELEMENT, ELEMENTID, ELEMENTID));

            return false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            SharedPreferences prefs = getPreferences(Activity.MODE_PRIVATE);
            Log.v("javascript2", String.format(JS_SETELEMENT, ELEMENTID, prefs.getString(ELEMENTID, "")));
            executeJavascript(view, String.format(JS_SETELEMENT, ELEMENTID,
                    prefs.getString(ELEMENTID, "")) );
        }
    };

    private void executeJavascript(WebView view, String script) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            view.evaluateJavascript(script, null);
        } else {
            view.loadUrl(script);
        }
    }

    private class MyJavaScriptInterface {
        @JavascriptInterface
        public void storeElement(String id, String element){
            SharedPreferences.Editor edit = getPreferences(Activity.MODE_PRIVATE).edit();
            edit.putString(id, element);
            edit.commit();
            if(!TextUtils.isEmpty(element)){
                Toast.makeText(MainActivity.this, element, Toast.LENGTH_SHORT).show();
            }
        }
    }
}
```