티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Android Calling JavaScript functions in WebView

WebView에서 JavaScript 함수 호출

 문제 내용 

I am trying to call some javascript functions sitting in an html page running inside an android webview. Pretty simple what the code tries to do below - from the android app, call a javascript function with a test message, which inturn calls a java function back in the android app that displays test message via toast.

나는 안드로이드 웹뷰 안에서 실행되는 html 페이지에 있는 자바스크립트 함수들을 호출하려고 한다. 코드가 아래에서 시도하는 것은 꽤 간단하다 - 안드로이드 앱에서 테스트 메시지와 함께 자바스크립트 함수를 호출하면, 이는 토스트를 통해 테스트 메시지를 표시하는 안드로이드 앱의 자바 함수를 다시 호출한다.

 

The javascript function looks like:

자바스크립트 함수는 다음과 같다:
function testEcho(message){
     window.JSInterface.doEchoTest(message);
}

 

From the WebView, I have tried calling the javascript the following ways with no luck:

WebView에서 Javascript를 다음과 같은 방법으로 호출하려고 했지만 실패했습니다.
myWebView.loadUrl("javascript:testEcho(Hello World!)");
mWebView.loadUrl("javascript:(function () { " + "testEcho(Hello World!);" + "})()");

 

I did enable javascript on the WebView

나는 웹뷰에서 자바스크립트를 활성화했다.
myWebView.getSettings().setJavaScriptEnabled(true);
// register class containing methods to be exposed to JavaScript
myWebView.addJavascriptInterface(myJSInterface, "JSInterface"); 

 

And heres the Java Class

그리고 여기 자바 클래스가 있다.
public class JSInterface{

private WebView mAppView;
public JSInterface  (WebView appView) {
        this.mAppView = appView;
    }

    public void doEchoTest(String echo){
        Toast toast = Toast.makeText(mAppView.getContext(), echo, Toast.LENGTH_SHORT);
        toast.show();
    }
}

 

I've spent a lot of time googling around to see what I may be doing wrong. All examples I have found use this approach. Does anyone see something wrong here?

나는 내가 무엇을 잘못하고 있는지 알아보기 위해 많은 시간을 보냈다. 내가 찾은 모든 예는 이 접근법을 사용한다. 여기서 뭐 잘못 본 사람 있나요?

 

Edit: There are several other external javascript files being referenced & used in the html, could they be the issue?

편집: html에서 참조 및 사용 중인 다른 외부 자바스크립트 파일이 몇 개 있는데, 문제가 될 수 있습니까?

 

 

 

 높은 점수를 받은 Solution 

I figured out what the issue was : missing quotes in the testEcho() parameter. This is how I got the call to work:

testEcho() 매개 변수에 따옴표가 없는 문제가 무엇인지 파악했습니다. 이렇게 하니 동작하였다.
myWebView.loadUrl("javascript:testEcho('Hello World!')");

 

 

 가장 최근 달린 Solution 

activity_main.xml

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

 

MainActivity.java


import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.bluapp.androidview.R;

public class WebViewActivity3 extends AppCompatActivity {
    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view3);
        webView = (WebView) findViewById(R.id.webView);
        webView.setWebViewClient(new WebViewClient());
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("file:///android_asset/webview1.html");


        webView.setWebViewClient(new WebViewClient(){
            public void onPageFinished(WebView view, String weburl){
                webView.loadUrl("javascript:testEcho('Javascript function in webview')");
            }
        });
    }
}

 

assets file

<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>WebView1</title>
<meta forua="true" http-equiv="Cache-Control" content="max-age=0"/>
</head>

<body style="background-color:#212121">
<script type="text/javascript">
function testEcho(p1){
document.write(p1);
}
</script>
</body>

</html>

 

 

출처 : https://stackoverflow.com/questions/4325639/android-calling-javascript-functions-in-webview

반응형
댓글
공지사항
최근에 올라온 글