WebView에서 javascript 실행

14090 단어 Android
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']
        }
    }
}

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에 데이터 저장
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();
            }
        }
    }
}

좋은 웹페이지 즐겨찾기