Calling javascript functions in a webview from activity class [closed]

让人想犯罪 __ 提交于 2019-12-12 08:50:53

问题


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);
    } 
}

来源:https://stackoverflow.com/questions/7916624/calling-javascript-functions-in-a-webview-from-activity-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!