How to autofill data inside webview? - javascript

I am stucked in one functionality. I am storing login credentials in my app for website. And there is one LOGIN button is there. When I hit that button, it will redirect to webview with website. And if there is any email and password, my login credentials will be filled there.
Example: I have stored facebook credentials in my app. And my webview is loading with https://m.facebook.com and when it will finish loading my stored login credentials will be filled there. So I just need to hit login button from webview to move forward.
For my app I am using following code. Which is not working for most website. Can anyone help me how to figure out this issue? Or does anyone has better idea to achieve this kind of functionality?
wvAutofill.loadUrl("https://mobile.twitter.com/login");
wvAutofill.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
final String js = "javascript: var x = document.getElementsByTagName(\"form\")[0].getElementsByTagName('input');" +
"for (var i = 0; i < x.length; i++) {" +
"\nconsole.log(x[i].type);" +
"var type = x[i].type;" +
"if (type=='text'){" +
"x[i].value=\"abc#gmail.com\";" +
"};" +
"if (type == 'password'){\n" +
"x[i].value=\"abc123\";" +
"}; " +
"if (type == 'button' || type == 'submit' || document.getElementsByTagName(\"button\")[0].tagName == \"button\"){" +
"x[i].click();" +
"}; " +
"}";
view.loadUrl(js);
}
});

Related

Wicket Strange behaviour of URL with ajax

I have issue that have strange steps. I have ajax behave rendered on Head render stage
final AbstractDefaultAjaxBehavior behave = new AbstractDefaultAjaxBehavior() {
protected void respond(final AjaxRequestTarget target) {
boolean undoEn = getRequest().getQueryParameters().getParameterValue("undoEn").toBoolean();
if (undoEn) {
mSaveButton.setEnabled(true);
target.add(mSaveButton);
}
}
};
public String getCallbackName() {
return "saveButtonVisibilityToggle";
}
#Override
public void renderHead(IHeaderResponse response) {
String script = getCallbackName() + " = function (e) { Wicket.Ajax.ajax({\"u\": \"" + behave.getCallbackUrl() + " + &undoEn=\"+e+\"\" });}";
response.render(OnDomReadyHeaderItem.forScript(script));
}
Everything works well this behave called every time node changed in tinyMCE editor
settings.addCustomSetting(" setup: function(editor) {" +
" editor.on('NodeChange', function(e) {" +
" editor.save();" +
getCallbackName() + "(editor.undoManager.hasUndo())" +
" });" +
" }");
But sometimes when i leave browser tab, change few tabs (chrome) then use other app for few minutes, and turn back to our tab, ajax url have accidently appeared in browser url.
http://localhost:8080/wicket/bookmarkable/com.tac.kulik.pages.SomePage?3-1.IBehaviorListener.0-contentPanel&entityId=2+++&undoEn=true
this is also quite strange that instead normap parameter pass it's ++++ signs added
by the way this sighns recognized as "2 " so for some reason '+' changed to whitespace
UPDATE 1
Using #svenmeier answer i've page start's infinite loop refreshing. with logs
org.apache.wicket.core.request.mapper.StalePageException: A request to
page '[Page class = x.x.x.CardPage, id = 25, render count = 1]' has been
made with stale 'renderCount'. The page will be re-rendered.
and really for some reason behave link has renderCount 1, but form has 0.
the request from browser
jquery-1.12.4-ver-1476216952000.js:10254 XHR finished loading: GET "http://localhost:8080/wicket/bookmarkable/com.tac.pages.ca…?4-0.IBehaviorListener.0-contentPanel&cardId=1&_=1476873175645&undoEn=true"
I ve add some set of JS to prevent cicling refreshing, But i'we still has Stale exception
"if (editor.undoManager.hasUndo()) { " +
" console.debug('Behave called ');" +
behave.getCallbackScript() +
" }" +
this is my behave
final AbstractDefaultAjaxBehavior behave = new AbstractDefaultAjaxBehavior() {
protected void respond(final AjaxRequestTarget target) {
log.info("Behave called");
boolean undoEn = getRequest().getQueryParameters().getParameterValue("undoEn").toBoolean();
if (undoEn) {
mSaveButton.setEnabled(true);
target.add(mSaveButton);
}
}
//
#Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
String undoEn = "return {'undoEn': editor.undoManager.hasUndo()};";
attributes.getDynamicExtraParameters().add(undoEn);
}
};
And there is no difference, it could be behave without any realization, page behaviour the same((
final AbstractDefaultAjaxBehavior behave = new AbstractDefaultAjaxBehavior() {
#Override
protected void respond(AjaxRequestTarget target) {
}
};
You should rework your behavior to use dynamic extra parameters instead.
#Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes)
{
super.updateAjaxAttributes(attributes);
String undoEn = "return {'undoEn': editor.undoManager.hasUndo()}";
attributes.getDynamicExtraParameters().add(undoEn);
}
And:
settings.addCustomSetting(
"setup: function(editor) {" +
" editor.on('NodeChange', function(e) {" +
" editor.save();" +
" " + getCallbackScript() + ";" +
" });" +
"}");

Website Login by using WebView Javascript Android

On Button click:
public void login(View v) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(rlayout.getWindowToken(), 0);
loginWebView.loadUrl("https://example.de");
loginWebView.setVisibility(View.INVISIBLE);
loginWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
loginWebView.loadUrl("javascript: {" +
"document.getElementById('login_act').value = '" + "USNAME" + "';" +
"document.getElementById('login_pwd').value = '" + "PWD" + "';" +
"document.getElementById('submit').click();" +
"};");
}
public void onPageFinished2(WebView view, String url) {
loginWebView.loadUrl(url);
}
});
loginWebView.clearCache(true);
loginWebView.clearHistory();
WebView view = (WebView) this.findViewById(R.id.mainwebView);
String url = "https://example.de";
view.loadUrl(url);
}
On Button click:
1- 1. WebView Login
2- 2. WebView show Page
3- Ready
At my first try all worked. No Error, no problems. The only thing was, that the WebView loaded with the page, where i was not logged in.
How can i log in and what went wrong ?
Try to replace:
public void onPageFinished(WebView view, String url) {
loginWebView.loadUrl("javascript: {" +
"document.getElementById('login_act').value = '" + "USNAME" + "';" +
"document.getElementById('login_pwd').value = '" + "PWD" + "';" +
"document.getElementById('submit').click();" +
"};");
}
With:
public void onPageFinished(WebView view, String url) {
loginWebView.loadUrl("javascript:{" +
"ins=document.getElementsByTagName('input');" +
"ins[0].value='usrn';" +
"ins[1].value='pwd';" +
"ins[2].value=true;" +
"document.getElementsByTagName('form')[0].submit();" +
"};" );
}
Replace for usrn your username and replace for pwd your password. Use ins[2].value=true to hit "remember me". (If there no "remember me" checkbox delete it)
The last entry hit the submit Button.
Main Sourcecode by Jonas w - https://stackoverflow.com/users/5260024/jonas-w
(Just an advanced comment):
"javascript:{
ins=document.getElementsByTagName('input');
ins[0].value='username';
ins[1].value='password';
ins[2].value=true;
document.getElementsByTagName('form')[0].submit();
}"
Das schreibt username ins erste, passwort ins zweite und setzt das Dritte auf true und schickt das erste formular ab...

Android String to WebView with Javascript

I am trying to get Intent data to the loaded WebView.
Before the intent, There was a EditText, and I originally used the values to login to myURL site with the WebView inside that Activity whitch had userID and userPW (at the site).
But for better design, I've move the Webview to another activity and sends the ID,PW with Bundle.
The problem is that the String variable email and password seems to be set well, but when i try to use the same code i used before, it doesn't work well.
Is there some rules in Android that i can't pass the variables directly without user input? Does someone know how to solve this problem?
Below is the code i'm currently stuck on
public class MyWeb extends Activity{
WebView webview;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_myweb);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
email = bundle.getString("ID");
password = bundle.getString("PW");
webview = (WebView)findViewById(R.id.logIn);
webview.setWebViewClient(new WebClient());
webview.getSettings().setDatabaseEnabled(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("myURL");
login(email, password);
}
private void login(String id, String pw){
webview.loadUrl("javascript: {" +
"document.getElementById('userID').value = '"+email +"';" +
"document.getElementById('userPW').value = '"+password+"';" +
"var a = document.getElementsByTagName('input');" +
"a[2].CheckSubmit(); };");
webview.loadUrl("javascript:CheckSubmit()");
}
webview.setWebViewClient(new WebClient() {
#Override
public void onPageFinished(WebView view, String url) {
webview.loadUrl("javascript: {" +
"document.getElementById('userID').value = '" + email + "';" +
"document.getElementById('userPW').value = '" + password + "';" +
"var a = document.getElementsByTagName('input');" +
"a[2].CheckSubmit(); };");
webview.loadUrl("javascript:CheckSubmit()");
}
});
Solved, I guess it was because of the JS was called before the webpage load thinking that the Activity before this loads all the page while i type in the fields

WebView code generating Uncaught TypeError and Uncaught ReferenceError errors on Android 4.4.2 (API 19) emulator

I'm having a problem with my code when running on a Android 4.4.2 KitKat (API 19) emulator...
When I emulate my project on a Android 4.3 (API 18) emulator, it works normally and creates the mathematical expressions with MathJax:
Image of emulator
But when I use a Android 4.4.2 emulator, the app don't work correctly:
Image of emulator
Here is the code of my project:
package com.testes.testesapp;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements View.OnClickListener {
private int exampleIndex = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
//webView.getSettings().setBuiltInZoomControls(true);
webView.loadDataWithBaseURL("http://test", "<script type='text/x-mathjax-config'>"
+ "MathJax.Hub.Config({ "
+ "showMathMenu: false, "
+ "jax: ['input/TeX','output/HTML-CSS'], " // output/SVG
+ "extensions: ['tex2jax.js','toMathML.js'], "
+ "TeX: { extensions: ['AMSmath.js','AMSsymbols.js',"
+ "'noErrors.js','noUndefined.js'] }, "
// + "'SVG' : { blacker: 30, "
// + "styles: { path: { 'shape-rendering': 'crispEdges' } } } "
+ "});</script>"
+ "<script type='text/javascript' "
+ "src='file:///android_asset/MathJax/MathJax.js'"
+ "></script>"
+ "<span id='math'></span>","text/html","utf-8","");
EditText edit = (EditText) findViewById(R.id.edit);
edit.setBackgroundColor(Color.LTGRAY);
edit.setTextColor(Color.BLACK);
edit.setText("");
Button btnShow = (Button) findViewById(R.id.btnShow);
btnShow.setOnClickListener(this);
Button btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(this);
Button btnExample = (Button) findViewById(R.id.btnExample);
btnExample.setOnClickListener(this);
}
private String doubleEscapeTeX(String s) {
String t="";
for (int i=0; i < s.length(); i++) {
if (s.charAt(i) == '\'') t += '\\';
if (s.charAt(i) != '\n') t += s.charAt(i);
if (s.charAt(i) == '\\') t += "\\";
}
return t;
}
private String getExample(int index) {
return getResources().getStringArray(R.array.tex_examples)[index];
}
public void onClick(View v) {
if (v == findViewById(R.id.btnShow)) {
WebView webView = (WebView) findViewById(R.id.webview);
EditText edit = (EditText) findViewById(R.id.edit);
webView.loadUrl("javascript:document.getElementById('math').innerHTML='\\\\["
+ doubleEscapeTeX(edit.getText().toString()) + "\\\\]';");
webView.loadUrl("javascript:MathJax.Hub.Queue(['Typeset',MathJax.Hub]);");
}
else if (v == findViewById(R.id.btnClear)) {
WebView webView = (WebView) findViewById(R.id.webview);
EditText edit = (EditText) findViewById(R.id.edit);
edit.setText("");
webView.loadUrl("javascript:document.getElementById('math').innerHTML='';");
}
else if (v == findViewById(R.id.btnExample)) {
WebView webView = (WebView) findViewById(R.id.webview);
EditText edit = (EditText) findViewById(R.id.edit);
edit.setText(getExample(exampleIndex++));
if (exampleIndex > getResources().getStringArray(R.array.tex_examples).length - 1)
exampleIndex=0;
webView.loadUrl("javascript:document.getElementById('math').innerHTML='\\\\["
+ doubleEscapeTeX(edit.getText().toString()) + "\\\\]';");
webView.loadUrl("javascript:MathJax.Hub.Queue(['Typeset',MathJax.Hub]);");
}
}
}
When I press the "Example" or the "Show" button, LogCat emits the errors:
I/chromium(1254): [INFO:CONSOLE(1)] "Uncaught TypeError: Cannot set property 'innerHTML' of null", source: http://test/ (1)
I/chromium(1254): [INFO:CONSOLE(1)] "Uncaught ReferenceError: MathJax is not defined", source: http://test/ (1)
I have no idea how to fix this problem, and would like somebody's help to solve this. Thanks.
I got this problem too.
Here is my solution:
change your base URL from "http://test" to "http://test/"
change this code webView.loadUrl(..) to webView.evaluateJavascript(..);. Especially for code where we want to load innerHTML. Don't forget to add anotation #TargetApi(Build.VERSION_CODES.KITKAT) because it's only for Android 4.4 and above
never put webView.loadWithBaseUrl(..) in the same process with webView.loadUrl(..). Because If webView.loadUrl(..) was loaded before webView.loadWithBaseUrl(..) finished, it will raise error as OP stated above.
For number 3, your codes is already conform with this (because in your codes, webView.loadUrl(..) execution was already separated with webView.loadWithBaseUrl(..) by using OnClick event. So, don't pay attention to it.
But if your apps need to load them at one event, consider to separate them by using this code:
`
private void initiateWebView(){
webViewEquationDisplay.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
loadUrlKitKat(equationSymbolFinal+equationToBeDisplayedFinal);
}
else{
webViewEquationDisplay.loadUrl("javascript:document.getElementById('math').innerHTML='<font color=\"yellow\">`"+equationToBeDisplayedFinal+"`</font>';");
}
webViewEquationDisplay.loadUrl("javascript:MathJax.Hub.Queue(['Typeset',MathJax.Hub]);");
}
});
final String mathJaxOfflineUrl = "file:///android_asset/MathJax/MathJax.js";
webViewEquationDisplay.loadDataWithBaseURL("http://bar/", "<script type='text/x-mathjax-config'>"
+"MathJax.Hub.Config({ "
+"showMathMenu: false, "
+"jax: ['input/AsciiMath','output/HTML-CSS'], "
+"extensions: ['asciimath2jax.js'], "
+"AsciiMath: { fixphi: true, useMathMLspacing: true, displaystyle: false, decimalsign: \".\" }, "
+"});</script>"
+"<script type='text/javascript' "
+"src='"+mathJaxOfflineUrl+"'"
+"></script><span id='math'></span>","text/html","utf-8","");
}
#TargetApi(Build.VERSION_CODES.KITKAT)
private void loadUrlKitKat(String param){
webViewEquationDisplay.evaluateJavascript("javascript:document.getElementById('math').innerHTML='<font color=\"#97FD97\">`"+param+"`</font>';",null);
}
`
good luck
I had the same problem when I moved different javascript functions out of the main page to an separate .js file. For some reason, Android can't find externally-loaded JavaScript webview functions from Java - only the ones in the main page. Once I moved the function back from the JS file, it immediately started working.
Try making a "proxy" function like this directly inside the main HTML:
function proxy() {
call_some_other_function_from_JS_file();
}
This worked for me. I'm sure there must be a way to get find these functions, because I didn't have this problem on iOS. Someone please comment if you know a better way.
webview.evaluateJavascript("javascript:document.getElementById('math').innerHTML='"+doubleEscapeTeX(questn)+"';",null);
webview.loadUrl("javascript:MathJax.Hub.Queue(['Typeset',MathJax.Hub]);");
This is the sollution for api 19 or above

Calling JS function from Android Activity

I am calling a simple JS function to set values of some html contents, but its not working
Here is the JS function
function SetEdits(name,email,pic,date)
{
document.getElementById("myPic").src=pic;
document.getElementById("fullname").value=name;
document.getElementById("email").value=email;
}
and here is the code from android activity
edit.loadUrl("edit.html");
edit.loadUrl("javascript:SetEdits('"+name+"','"+email+"','"+picture+"','"+date+"')");
its not settings these fileds.. is there any problem with the synax where i am calling this function in native activity?
You're probably ending up evaluating the JavaScript before the "edit.html" page has loaded. Try this:
// I'm assuming the real path is something like file:///android_asset/edit.html
edit.loadUrl("edit.html");
edit.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if (Uri.parse(url).getPath() == "edit.html") {
view.loadUrl("javascript:SetEdits('" + name+"','" + email + "','" +
picture + "','" + date + "')");
}
}
Have you enabled the javascript for the webview ?
You have to setup a javascript interface between your app and html.
Here is some details Webapp guid

Categories

Resources