-->

Calling javascript functions in a webview from act

2019-04-07 15:15发布

问题:

Edit: This snipped worked in the end. I had been trying this before but was actually experiencing a scoping issue with my javascript. I had appBack() defined in document.onready. Simply re-scoping that function to *window.*appBack = function(). Done the business. Hope this helps someone.

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        WebView.loadUrl("javascript:appBack()");
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

Within a webview application the back navigation is handled with a custom JS function appBack() I've been trying to figure out a way to intercept the android physical back button and call that javascript function instead. Here is my activity file. Its very basic, sets up a webview and listens for the back button click. Currently when the user clicks this physical back button it runs mWebView.goBack(). Which is where I would like to perform javascript:appBack()

package com.stgeorgeplc.app;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;


public class StGeorgePLCliteActivity extends Activity {
    /** Called when the activity is first created. */
    WebView mWebView;
    @Override

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setBuiltInZoomControls(true);

        mWebView.loadUrl("file:///android_asset/www/index.html");
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    } 
}