Using Javascript in webview - javascript

So, reading around i read that i could "inject" javascript into a loaded webpage to programatically fill a website's form, so i tried the following:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView WebView;
WebView = (WebView) findViewById(R.id.webview);
WebView.setWebViewClient(new HelloWebViewClient());
WebView.getSettings().setJavaScriptEnabled(true);
WebView.getSettings().setBlockNetworkImage(false);
WebView.loadUrl("http://www.kingsage.es");
String username = "XXX";
String Password = "YYY";
WebView.loadUrl("javascript:document.getElementById('login_player').value='"+username+"';javascript:document.getElementById('login_passwd').value = '"+Password+"';");
}
However, when i run this on the emulator i get an error as if the website could not be found. if i turn off the second loadUrl method i load the website, but i need to fill the login form programatically!, i figure i am doing something wrong but i haven't found and answer reading around. Any help would be appreciated!!

you need to wait until the webpage is loaded (use WebViewClient) then execute your javascript
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished (WebView webView, String url)
{
webView.loadUrl("javascript:document.getElementById('login_player').value='"+username+"';javascript:document.getElementById('login_passwd').value = '"+Password+"';");
}
});
make also sure that you execute only once, not on every onPageFinished Event

I like JeanLuc's suggestion and it worked for me 98% of the way. I still needed to automatically log the user into the web page once their username and password had been entered so I did the following and its worked well, except for trying to remove the "do you want to remember the password' message.
#Override
public void onPageFinished (WebView webView, String url)
{
webView.loadUrl("javascript:document.getElementById('Login1_UserName').value='"+userName+"';javascript:document.getElementById('Login1_Password').value = '"+password+"';");
webView.loadUrl("javascript:document.getElementById('Login1_LoginButton').click();");
}
The second line selected the 'login' button and logged them in automatically. Hope it helps someone else.

Here is how I acheived it in my scenario where I had to browse a page, fill text boxes and submit.
WebView webView = FindViewById<WebView>(Resource.Id.webEspView);
webView.SetWebViewClient(new Client());
webView.Settings.JavaScriptEnabled = true;
webView.LoadUrl("http://192.168.4.1")
Then added the Client class and overloaded onPageFinished() method.
public class Client : WebViewClient
{
public override void OnPageFinished(WebView view, string url)
{
base.OnPageFinished(view, url);
string ssid = Variables.GetInitialUsername();
ssid = ssid.Trim(new char[] {'\"'});
string pass = Variables.GetInitialPassword();
var script = $"document.getElementById(\"clientId\").value = \"{ssid}\";" +
$"document.getElementById(\"branchId\").value = \"{pass}\";" +
"document.querySelector('button[type=\"submit\"]').click()";
view.LoadUrl($"javascript: {script}");
}
}
Hope it helps.

Related

Set TextBox value with js injection in a WebView

Using Android Studio I am trying to set the value of a textbox in a login form of a web page which is not mine.
Here's the webView i use to work on the page:
final WebView webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
webView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(WebView view, String url)
{
webView.loadUrl("javascript: document.getElementById('j_password').value = 'something'");
}
});
webView.loadUrl("http://sg18224.scuolanext.info/");
the problem is that when the page has finished loading instead of setting the textbox value, the whole page becomes white and it only displays the string i was trying to set as value (in this case "something").
If i include the js line in an alert like this:
webView.loadUrl("javascript: alert(document.getElementById('j_password').value = 'something')");
it works! But also displays an alert i don't want to display.
This should help you:
final String js = "javascript:document.getElementById('j_password').value='something';";
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if (Build.VERSION.SDK_INT >= 19) {
view.evaluateJavascript(js, new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) { }
});
} else {
view.loadUrl(js);
}
}
});
I am not sure with this answer but you may try it. typically it should be the answer. Long time no interaction with javascript though.
you may try
webView.loadUrl("javascript: document.getElementById('j_password').innerHTML = 'something'");
please comment if its not working.

javascript and webview in android

I am a beginner in android platform and making an app with help of webview and javascript.when I run my code on real device it displays nothing.any help would be appreciable.
Here is my code:
public class MainActivity extends AppCompatActivity {
WebView view_1,view_2;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
String url_1="<script type=\"text/javascript” src=\"http://ds.claymcenter.com/embed.js\">\n" +
"requestAd('Rh8uGpcrlYMjXN1s', 'banner', 'ads', '320' , ‘50');\n" +
"</script>\n" +
" \n" +
"<div id='ads'></div>";
String url_2="https://paytm.com/";
view_1 = (WebView) findViewById(R.id.webViewGoogle);
view_2 = (WebView) findViewById(R.id.webViewFacebook);
view_1.getSettings().setJavaScriptEnabled(true);
view_1.loadData(url_1, "text/html", null);
view_2.getSettings().setJavaScriptEnabled(true);
view_2.loadUrl(url_2);
imageView = (ImageView) findViewById(R.id.imageView);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
view_1.reload();
view_2.reload();
}
});
} }
I always have a hell of a time trying to get things like this to work, and I don't remember exactly how I did some of this stuff, but here are some ideas:
First thing to try: Wrap that string in url_1 in <html><body>...</body></html> tags.
Second thing to try: You might have to use some kind of "onDocumentReady" event to call your javascript when the js file is completely loaded.
Third thing thing to try: Split out the function call like so:
String url_1="<script type=\"text/javascript\” src=\"http://ds.claymcenter.com/embed.js\">\n" +
"</script>\n" +
"<div id='ads'></div>";
String call = "javascript:requestAd('Rh8uGpcrlYMjXN1s', 'banner', 'ads', '320' , ‘50');\n"
Load the html with the js file then use WebViewClient.onPageFinished() to see when to load the javascript call (don't cut & paste this code, this is just a template):
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
// TODO: need to find out what is in url when html with js file loads
if (urlMatches()) {
view.loadData(call, "application/javascript", null); // not sure about the mime type
}
}
});
This is like "onDocumentReady" but doing it in the Java code.
You might be getting stuck because of this statement from the loadData docs:
Note that JavaScript's same origin policy means that script running in a page loaded using this method will be unable to access content loaded using any scheme other than 'data', including 'http(s)'. To avoid this restriction, use loadDataWithBaseURL() with an appropriate base URL.
So the last thing to try would be using loadDataWithBaseURL.

shouldoverrideurlloading not called Webview Android

First of all , this post may ,look like a Possible Duplicate of other question, but I have go through many questions but found them not helpful.
Now My problem is that I am loading an URL in my Webview and then I want to Trace URL on each event on webview so I have set up WebviewClient for Webview and overridden shouldoverrideurlloading method, but after first Event , shouldoverrideurlloading not getting called. (worked first time)
Here is the Code I have used :
wvSecurity = (WebView) findViewById(R.id.wvSecurity);
wvSecurity.getSettings().setJavaScriptEnabled(true);
wvSecurity.getSettings().setAllowContentAccess(true);
wvSecurity.getSettings().setAllowUniversalAccessFromFileURLs(true);
wvSecurity.getSettings().setBuiltInZoomControls(false);
wvSecurity.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wvSecurity.getSettings().setLoadWithOverviewMode(true);
wvSecurity.getSettings().setDomStorageEnabled(true);
wvSecurity.loadUrl("URL");
wvSecurity.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view,
final String urlStr) {
Log.i("URL", "::" + urlStr);
return false;
}
}
EDIT ::
Ok, The URL which I want to Trace uses POST method , Now my question is How can I trace POST URL and its data. And one thing , I dont have access to Webpage coming in so I simply cant go for GET method. Please Help !!!
I guess this method gets called when a hyperlink is tapped from page or some redirection happens. So make sure this thing.
I think you need to pass the url in place on "URL" so this will solve your problem.
wvSecurity = (WebView) findViewById(R.id.wvSecurity);
wvSecurity.getSettings().setJavaScriptEnabled(true);
wvSecurity.getSettings().setAllowContentAccess(true);
wvSecurity.getSettings().setAllowUniversalAccessFromFileURLs(true);
wvSecurity.getSettings().setBuiltInZoomControls(false);
wvSecurity.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wvSecurity.getSettings().setLoadWithOverviewMode(true);
wvSecurity.getSettings().setDomStorageEnabled(true);
wvSecurity.loadUrl("http://www.google.com");
wvSecurity.setWebViewClient(new HelloWebViewClient());
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println("URL :: " + url);
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, final String url) {
}
}

webview cant be refresh using anyway

i have web view and i try to give the user button to refresh but i cant set that button i try to use this code
the refresher button
imgbtr2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ImageButton imgbtr2 = (ImageButton) findViewById(R.id.imageButtonr2);
WebView webView = (WebView)findViewById(R.id.webView);
webView.loadUrl("javascript:window.location.reload(true)"); // TODO Auto-generated method stub
}
});
the webview
webView = (WebView) findViewById(R.id.webView1);
webView.loadUrl("http://m.facebook.com/");
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
but it seems like javascript:window.location.reload(true) its not work . if i use webView.loadUrl("www.exapml.com"); it will work but this is not last Url u was there not reopen the webpage from the first url
and why webview can not open page like https://vine.co/ is it coz its not end with .com .. and how to make it open all the website .. and when u enter website like Myspace and try to login using Facebook everything will work ok until u finish login it will not show anything after u connect it to ur facebook ,, is it coz of the redirection and if it is how to fix it
this is the last 3 thing's stop me from finishing my app . i hope someone can help
Use web.reload(); method to do so.
imgbtr2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
web.reload();
}
});
Call again
mWebView.loadUrl("http://www.facebook.com");
so the full code would be
newButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dgeActivity.this.mWebView.loadUrl("http://www.facebook.com");
}});

JavaScript alert not working in Android WebView

In my application I am using WebView and in that I am using JavaScript alert( ) method but its not working, no pop-up appears.
in my manifest file I have added
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
and in activity file I have added
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("file:///android_asset/demo.html");
In layout xml file I have added
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
Any clue how to enable full JavaScript in WebView?
Update
Thanks mark
the alert() method in the html file are working now :) .
Now there are two issues in WebView :
1: I am using a <textarea> in the html file that i am loading in WebView , and trying to write in Hindi language font in it, but when i try to write Hindi text it displays as symbols ( rectangle symbols like [] ) .
when i do the same in firefox browser on desktop it works fine.
any clue how to give support for multiple language in textarea in WebView ?
2: When I am clicking submit and trying to open the value of text in alert() method in another java script it doesn't work , does it mean even after using WebChromeClient
its applicable only for current loaded html page and not javascripts called from that page ?
As others indicated, setting the WebChromeClient is needed to get alert() to work. It's sufficient to just set the default WebChromeClient():
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient());
Thanks for all the comments below. Including John Smith's who indicated that you needed to enable JavaScript.
Check this link , and last comment , You have to use WebChromeClient for your purpose.
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
return super.onJsAlert(view, url, message, result);
}
});
The following code will work:
private WebView mWebView;
final Activity activity = this;
// private Button b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setProgress(progress * 1000);
}
});
mWebView.loadUrl("file:///android_asset/raw/NewFile1.html");
}
You can try with this, it worked for me
WebView wb_previewSurvey=new WebView(this);
wb_previewSurvey.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//Required functionality here
return super.onJsAlert(view, url, message, result);
}
});
if you wish to hide URL from the user, Show an AlertDialog as below.
myWebView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.d(TAG, "onJsAlert url: " + url + "; message: " + message);
AlertDialog.Builder builder = new AlertDialog.Builder(
mContext);
builder.setMessage(message)
.setNeutralButton("OK", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
}
}).show();
result.cancel();
return true;
}
}

Categories