Android WebView Compile a Form and submit with Jav

2019-02-19 14:41发布

问题:

I'm trying to complete this form :

http://www.lbalberti.it/whatsup.asp?codist=57247

I was able to insert value to the two textbox but the button doesn't work.

@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_page);
    final String user = getIntent().getStringExtra("username");
    final String psw = getIntent().getStringExtra("password");

    MyWebView view = new MyWebView(this);
    view.getSettings().setJavaScriptEnabled(true);
    view.getSettings().setDomStorageEnabled(true);
    view.loadUrl("http://www.lbalberti.it/whatsup.asp?codist=57247");
    view.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView v, String url) {
            v.loadUrl(url);
            return true;
        }
        @Override
        public void onPageFinished(WebView v, String url) {
            v.loadUrl("javascript:" +
                    "var y = document.getElementsByName('login')[0].value='"+user+"';" +
                    "var x = document.getElementsByName('password')[0].value='"+psw+"';");
}
    });
    setContentView(view);
}

class MyWebView extends WebView {
    Context context;
    public MyWebView(Context context) {
        super(context);
        this.context = context;
    }
}

The following code doesn't work :
"var k = document.getElementByTagName('form')[0].submit();"
or
"var k = document.getElementByName('newlogin')[0].submit();"

回答1:

 @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            view.evaluateJavascript("javascript:document.getElementById('username').value ='" + strUsername + "';javascript:document.getElementById('password').value = '" + strPassword + "';javascript:document.getElementById('loginButton').click();", null);
        } else {
            view.loadUrl("javascript:document.getElementById('username').value = '" + strUsername + "';javascript:document.getElementById('password').value = '" + strPassword + "';javascript:document.getElementById('loginButton').click();");
        }

}