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")
Related
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);
}
I'm trying to interact with a Website "synchronously" (javascript events when submit buttons are clicked) in order to get a textField value. This textField doesn't exist in the first place. It is generated when the user clicks on a submit button from a HTML form (2 buttons actually : first one : Id = "ColumnLeft_ADD_BTN_ID", second one : Id = "ColumnLeft_GET_BTN_ID").
When I simulate a click with Javascript, the textField doesn't appear. I get this error "Uncaught TypeError: Cannot read property 'value' of null" because the textField doesn't exist.
I've tried HTMLUnit but I couldn't make it work with Android. I turned to Android WebView.
Here's my code :
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(url);
final String js = "(function() { " +
"document.getElementById('ColumnLeft_RES_TB_ID').value='" + group + "';" +
"document.getElementById('ColumnLeft_ADD_BTN_ID').click();" +
"document.getElementById('ColumnLeft_GET_BTN_ID').click();" +
"return document.getElementById('ColumnLeft_FEED_URL_TB_ID').value; " +
"})();";
mWebView.setWebViewClient(new WebViewClient(){
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) {
JsonReader reader = new JsonReader(new StringReader(s));
// Must set lenient to parse single values
reader.setLenient(true);
try {
if(reader.peek() != JsonToken.NULL) {
if(reader.peek() == JsonToken.STRING) {
String msg = reader.nextString();
Log.d("DEBUG", "msg : " + msg);
}
}
} catch (IOException e) {
Log.e("TAG", "MainActivity: IOException", e);
} finally {
try {
reader.close();
} catch (IOException e) {
// NOOP
}
}
}
});
}
}
});
I have a simple javascript where I want to give value to these input which is username and password. I open the website by using webview. When the webview fully loaded, the username and password place doesn't change at all.
The website : http://www.malaysiakini.com/login/en/form
My source code for the javascript :
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript: {" +
"$('input#username').val(" + user + ");\n" +
"$('input#username').val(\"password\");\n" +
"document.querySelectorAll(\"button[type='submit']\")[0].click();}");
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript: {" +
"$('input#username').val('" + user + "');\n" +
"$('input#username').val(\"password\");\n" +
"document.querySelectorAll(\"button[type='submit']\")[0].click();}");
}
Silly me, I missed the single quotes
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.
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