WebView with Javascript keep reloading - javascript

I am using a WebView to display a website into my application.
When I'm loading my WebView, I first need to fill the authentification form and then redirect to the original URL.
My WebView keep reloading again and again.
Could anyone explain to me how to use a WebView with "automatic" filling please?
final WebView mWebView;
//Show webview into the app via a popup
AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(context);
mAlertDialog.setTitle(R.string.menuBuyCredit);
mWebView = new WebView(context);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(ConstantsClass.URL_BUY_CREDIT);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//In order to automatically fill the form
final String mJavaScript = "javascript:" +
"document.getElementById('Login').value = '" + ClientSingleton.getInstance().getmLogin() + "';" +
"document.getElementById('Password').value = '" + ClientSingleton.getInstance().getmPassword() + "';" +
"document.getElementById('Btn_Envoyer').click()";
view.loadUrl(mJavaScript);
view.loadUrl(ConstantsClass.URL_BUY_CREDIT);
view.pageDown(true);
}
});
mAlertDialog.setView(mWebView);
mAlertDialog.setNegativeButton(R.string.closeDrawer, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
mAlertDialog.show();
} ```

You should use something like
Put this in global
boolean loadedAlready = false;
inside onPageFinished method
if (view.getUrl().equals(ConstantsClass. URL_BUY_CREDIT) && !loadedAlready) {
loadedAlready= true;
view.load(ConstantsClass.URL_BUY_CREDIT);
}

Related

How to logout from a website running in an Android Webview?

This is my code for handling login:
wblogin.getSettings().setJavaScriptEnabled(true);
wblogin.loadUrl("http://mywebsite.com/login.php");
wblogin.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
wblogin.loadUrl("javascript: {" +
"document.getElementById('email').value = '" + user_name + "';" +
"document.getElementById('password').value = '" + pass_name + "';" +
"document.getElementById('xyz').click();" +
"};");
}
});
When I logout from the website running in Webview it starts to login automatically
Have you turned on a setting like "Remember my login" for the login page? Maybe it is a default checkbox set?
Second idea: Maybe the auto login after logout happens because of cookies set. Find information how to disable cookies in a webview here and here
There is no really pretty and short way in doing so.
The problem is that everytime you load a new page you run the code for logging in on every single page.
To work around that problem you should save wether you already logged into the application, simplest approach is as follows:
wblogin.setWebViewClient(new WebViewClient() {
private boolean shallLogin = true;
#Override
public void onPageFinished(WebView view, String url) {
if (shallLogin == true) {
wblogin.loadUrl("javascript: {" +
"document.getElementById('email').value = '" + user_name + "';" +
"document.getElementById('password').value = '" + pass_name + "';" +
"document.getElementById('xyz').click();" +
"};");
shallLogin = false;
}
}
});
As the login might fail or the user might move around without being logged in a more proper way would be to register a JS Callback and on page reload check if the login were successful by finding an element by ID which is only visible when logged in like the userimage or something.
...
#Override
public void onPageFinished(WebView view, String url) {
wblogin.loadUrl("javascript: {" +
"window.ANDROID_CALLBACK.login(document.getElementsByClassName('.my-user-img').length > 0);"
"};");
}
...
class LoadListener {
public LoadListener (MyWebViewClient myWebViewClient) {
}
public void login(boolean loginWorked) {
wblogin.shallLogin = !loginWorked;
}
}
...
wblogin.addJavascriptInterface(new LoadListener(wblogin), "ANDROID_CALLBACK")

Android Javascript function only works on initial load

In my Android Application, I have a WebView, before it displays anything from it though, I made it so that certain elements on my site do not display with javascript.It however only works on the first load, if you actually navigate through the site(click on a post for example) it will display all of the elements I don't want it to. It was working perfectly fine before, and now I cannot figure out why it isn't working. I'd appreciate any help!
mWebView = (WebView) view.findViewById(R.id.webView);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
return false;
}
#Override
public void onPageStarted(final WebView view, final String url, final Bitmap favicon) {
bar.setVisibility(View.VISIBLE);
mWebView.setVisibility(View.INVISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url)
{
mWebView.loadUrl("javascript:(function() { " +
"document.getElementsByClassName('fa fa-youtube')[0].style.display='none'; " +
"document.getElementsByClassName('fa fa-twitter')[0].style.display='none'; " +
"document.getElementsByClassName('menu-primary-container')[0].style.display='none'; " +
"document.getElementsByClassName('menu-toggle')[0].style.display='none'; " +
"document.getElementsByClassName('widget_slider_area')[0].style.display='none'; " +
"})()");
bar.setVisibility(View.GONE);
mWebView.setVisibility(View.VISIBLE);
super.onPageFinished(view, url);
}
});
mWebView.loadUrl("http://mywebsite.com");

Unable to set text in android webview using javascript

I have a webview with following settings :
mView.getSettings().setLoadWithOverviewMode(true);
mView.getSettings().setUseWideViewPort(false);
mView.getSettings().setJavaScriptEnabled(true);
mView.getSettings().setAllowContentAccess(true);
mView.getSettings().setDomStorageEnabled(true);
After loading a webpage, when I try to execute Javascript:
mView.loadUrl("javascript:document.querySelector('input[type=password]').value ='" + password + "'");
It opens a new tab or window instead of setting the value of password field.
Output of document.querySelector('input[type=password]') (from console) :
<input type="password" name="userpassword" id="userpassword" maxlength="6" style="width: 128px; height: 18px">
I tried executing the same javascript from console. It works!
I have also configured webviewclient:
mView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d(TAG, " shouldOverrideUrlLoading :" + url);
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
Log.d(TAG, "onPageStarted " + url);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Log.e(TAG, "Error: " + description);
}
});
loadUrl method, loads the provided URL in the WebView. What you have to do is execute the evaluateJavascript method.
webView.evaluateJavascript("document.querySelector('input[type=password]').value ='" + password + "'", new ValueCallback<String>() {
#Override
public void onReceiveValue(String value) {
/// This callback is called after a result is returned by the script.
}
});
As of Android Kitkat (4.4, API level 19), you can use evaluateJavascript.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("js_code", null);
} else {
webView.loadUrl("javascript:js_code");
}
You are forgetting quotes on your CSS selector.
It should be:
document.querySelector('input[type="password"]');
See jsfiddle

The HTML with javascript is not getting loaded in android webview

I am trying to display a page containing HTML with javascript in android webview with the below code.But this doesn't seem to work.Can anyone help me out.
public class MainActivity extends ActionBarActivity {
WebView browser;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
browser = (WebView) findViewById(R.id.webView);
browser.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
browser.setWebViewClient(new Callback());
browser.getSettings().setJavaScriptEnabled(true);
loadTime();
}
void loadTime() {
String page = "<html>"
+"<head>"
+"<title>chat window</title>"
+"<script type=\"text/javascript\">"
+ "var bccbId = Math.random(); document.write(unescape('%3Cdiv id=' + bccbId + '%3E%3C/div%3E'));"
+" window._bcvma = window._bcvma || [];"
+" _bcvma.push([\"setAccountID\", \"423771628801258096\"]);"
+" _bcvma.push([\"setParameter\", \"WindowParameters\", \"vr=&vi=&ve=" + gblQnbVars["gUserEmail"] + "&vp=" + gblQnbVars["gMobileNum"] + "&vn= "+ gblQnbVars["gCustomerFirstName"]+ "&lc=\"]);"
+"var bcLoad = function(){"
+ " if(window.bcLoaded) return; window.bcLoaded = true;"
+" var vms = document.createElement(\"script\");"
+"vms.type = \"text/javascript\";"
+" vms.async = true;"
+" vms.src = ('https:'==document.location.protocol?'https://':'http://') + \"vmss.boldchat.com/aid/423771628801258096/bc.vms4/vms.js\";"
+"var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(vms, s);"
+"};"
+"if(window.pageViewer && pageViewer.load) pageViewer.load();"
+" else if(document.readyState==\"complete\") bcLoad();"
+" else if(window.addEventListener) window.addEventListener('load', bcLoad, false);"
+" else window.attachEvent('onload', bcLoad);"
+ "function FireBoldChat() {"
+" try {"
+ " _bcvmw.chatWindow({"
+ "type: \"chat\","
+ "rdid: \"\","
+ "cwdid:\"1504531236710990857\","
+ "ve:\"<%=visitor email%>\","
+ "vp:\"<%=visitor phone%>\","
+ "vn:\"<%=visitor name%>\","
+ "embed: true"
+ "});"
+" } catch (e) {"
+"setTimeout(FireBoldChat, 500)"
+" }"
+" };"
+" </script>"
+"</head>"
+"<body onload=\"FireBoldChat();\">"
+"</body>"
+"</html>";
System.out.println(page);
browser.loadDataWithBaseURL("x-data://base", page,
"text/html", "UTF-8",
null);
}
private class Callback extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
loadTime();
return(true);
}
}
Whenever I load my this webpage in default browser its working perfectly. Where i have did wrong.
The documentation for loadData() says
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.
Now you do use loadDataWithBaseURL(), but your base URL is x-data://base yet you try to load a script from http(s)://vmss.boldchat.com. I think that can cause your problem.
I got same problem. I just replace
vms.src="https://" +\"vmss.boldchat.com/aid/423771628801258096/bc.vms4/vms.js\";"
this will be come if not add necessary java script file
before run please check your XML format is ok
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
for more :http://developer.android.com/guide/webapps/webview.html
and you may not call layout
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
WebView webView = (WebView)
browser = findViewById(R.id.webview);
browser.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
browser.setWebViewClient(new Callback());
browser.getSettings().setJavaScriptEnabled(true);
}
}
try this some time this will be help
thank
Looking at your code, didn't see the run time changes in html file.
So create html file using above page variable & put in assets folder.
once this done write following code:
public class ViewWeb extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
WebView vistaWeb = (WebView) findViewById(R.id.webView1);
vistaWeb.setWebChromeClient(new Callback());
vistaWeb.setWebViewClient(new Callback());
vistaWeb.clearCache(true);
vistaWeb.clearHistory();
vistaWeb.getSettings().setJavaScriptEnabled(true);
vistaWeb.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
vistaWeb.loadUrl("file:///android_asset/aboutcertified.html"); // now it will not fail here
}
}
Hope this will help you.
I suspect the variable gblQnbVars I did not find any reference to it in your snippet. Can you confirm if it is accessible in your code? May be that's throwing error.

Android : Inject JavaScript before loading the URL in webview

I'm developing one application in which a URL is loaded in webview of the app. Through JavaScript I'm slicing out the header and footer of the webpage and showing content in the webview. My problem is that, it takes some time to slice out the header and footer of the webpage, for about 1-2 secs the header is visible and hide that immediately. I'm attaching my WebViewClient class :
private class CustomWebClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
progress.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
doGet(url);
return true; // super.shouldOverrideUrlLoading(view, url);
}
public void onLoadResource(WebView view, String url) {
webview.loadUrl("javascript:(function() { "
+ "document.getElementsByTagName('header')[0].style.display = 'none'; "
+ "})()");
webview.loadUrl("javascript:(function() { "
+ "document.getElementsByTagName('footer')[0].style.display = 'none'; "
+ "})()");
webview.loadUrl("javascript:(function() { "
+ "document.getElementsByTagName('section').search_again.style.display = 'none'; "
+ "})()");
}
}
On onLoadResource() method I'm injecting JS.
Anyone has got some idea about the problem I'm facing, please help me in overcoming this problem.
You can use a css file with media queries for android to hide the header/footer over css

Categories