Issue
i build new android app and use java script syntax document.getElementsByName('') to insert value in input field in web page . but not working in some web page that i load it in web view in android studio
here the code
webCollection =(WebView)findViewById(R.id.webCollection);
webCollection.getSettings().setJavaScriptEnabled(true);
webCollection.getSettings().setDomStorageEnabled(true);
webCollection.loadUrl("mywepSite");
webCollection.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:(function(){document.getElementsByName('j_username')[0].value='myUser';document.getElementsByName('j_password')[0].value='MyPassword';document.getElementsByTagName('form')[0]();})()");
}
});
}
});
here the input field
<input name="j_username" tabindex="1" class="form-control input-lg margin-bottom" id="j_username" spellcheck="false" type="text" size="15" autocapitalize="off" autocorrect="off" autocomplete="off" data-required="Please enter required fields.">
<input name="j_password" tabindex="1" class="form-control input-lg margin-bottom" id="j_password" spellcheck="false" type="text" size="15" autocapitalize="off" autocorrect="off" autocomplete="off" data-required="Please enter required fields.">
Solution
this is a working class that can load a webview successfully
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import android.annotation.TargetApi;
public class Main extends Activity {
private WebView mWebview ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
final Activity activity = this;
mWebview.setWebViewClient(new WebViewClient() {
@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
@TargetApi(android.os.Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
// Redirect to deprecated method, so you can use it in all SDK versions
onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
}
});
mWebview .loadUrl("http://www.google.com");
setContentView(mWebview );
}
}
Dont forget to add Permission
<uses-permission `android:name="android.permission.INTERNET" />
Answered By - TanvirChowdhury
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.