WebView 안에서 자바스크립트 함수를 호출하여 액티비티 안의 함수를 호출할 수 있다.
새로운 액티비티를 호출하거나 데이터를 fetch할 때 사용된다.
WebView 안에서 자바스크립트 함수를 호출하여 액티비티 안의 함수를 호출할 수 있다.
새로운 액티비티를 호출하거나 데이터를 fetch할 때 사용된다.
WebView 에 등록할 인터페이스를 만든다. 인터페이스의 함수는 자바스크립트에서 호출할 때 사용된다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | final class MyJavaScriptInterface { MyJavaScriptInterface() { } /** * This is not called on the UI thread. Post a runnable to invoke * loadUrl on the UI thread. */ public void callAndroid( final String str) { mHandler.post( new Runnable() { public void run() { textView.setText(str); } }); } } |
WebView 에 자바스크립트 인터페이스 클래스를 등록하고 이름을 준다. webview.addJavascriptInterface(new MyJavaScriptInterface(), "myJs");
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_PROGRESS); setContentView(com.misun.samples.R.layout.sample07_a); webview = (WebView)findViewById(com.misun.samples.R.id.s07_webview); textView = (TextView)findViewById(com.misun.samples.R.id.s07_textview); WebSettings webSet = webview.getSettings() ; webSet.setJavaScriptEnabled( true ) ; webSet.setBuiltInZoomControls( true ); webview.addJavascriptInterface( new MyJavaScriptInterface(), "myJs" ); } |
자바스크립트에서 인터페이스 함수를 호출한다. window.myJs.callAndroid(str);
1 2 3 4 | function callAndroid(){ var str = myFrm.mytxt.value; window.myJs.callAndroid(str); } |
1 2 3 4 5 6 7 | < form id = "myFrm" action = "" > < input id = "mytxt" type = "text" > < button onclick = "javascript:callAndroid()" >호출하기</ button > </ form > |
Webview의 입력창에 글자를 입력하고 버튼을 누르면 상단 TextView 에 해당글자가 나타난다.
출처 - http://angmang.tistory.com/274