AndroidのWebViewで、Webページ内のjavascript実行時にJSON形式の値を渡す

レイアウトにWebViewを追加。

<WebView
    android:id="@+id/webView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:scrollbarStyle="insideOverlay"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent">
</WebView>

Java側でWebViewの取得、ひとまずアプリ内のローカルのhtmlを読み込む。

・・・
    private WebView webView;
・・・
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        webView = findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.setInitialScale(1);
        webView.loadUrl("file:///android_asset/index.html");

JSONを引数に渡して、javascriptを実行する。

        Gson gson = new Gson();
        Map<String, Object> data = new HashMap<>();
        data.put("data1", "XXXXXXX");
        data.put("data2", 10000);
        String script = "sampleFunc1(" + gson.toJson(data) + ")";
        webView.evaluateJavascript(script, null);

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

CAPTCHA