I have seen this question floating around the internet, but I haven't found a working solution yet. Basically, I want to load my app and press a button; the button action will then fill in a username and password in a website already loaded in the webview (or wait for onPageFinished). Finally, the submit button on the login page will be activated.
From what I understand this can be done by doing a java injection with the loadUrl(javascript), but I don't know what the java commands would be to fill in the fields. The same question was asked for iOS, but the commands are slightly different.
Is it possible to do what I am asking with javascript in a webivew, or do I have to do a http-post without a webview like this or this?
Thank you so much for any help you can give!
Thanks all for your answer, it helped me, but didn't work.
It was allways opening a white page until i found this :
https://stackoverflow.com/a/25606090/3204928
So here complete solution, mixing all infos found here and there :
1) first of all you have to enable DOM storage, if you don't do that, .GetElementByXXX will return nothing (you have to do it before loading the page)
myWebView.getSettings().setDomStorageEnabled(true);
2)Your last Javascript call on GetElementByXXX MUST store the result in a variable
Exemple 1 :
_webview.loadUrl("javascript:var uselessvar =document.getElementById('passwordfield').value='"+password+"';");
here only one call (only one semi-colon) so we immediatly store the result in 'uselessvar'
Example 2 : see user802467 answer
here there is 3 calls (one for login field, one for password field, one to submit button), only the last call need to be store, it's done in 'frms'
Javascript programmers should easily explain this behaviour...
hope this will help
You don't need to use "java commands"... but instead JavaScript... for instance:
String username = "cristian";
webview.loadUrl("javascript:document.getElementById('username').value = '"+username+"';");
So basically, what you have to do is a big string of JavaScript code that will get those fields and put values on them; also, you can enable/disable the submit button from JavaScript.
This worked for me to fill form values and submitting the form:
webView.loadUrl("javascript: {" +
"document.getElementById('username').value = '"+uname +"';" +
"document.getElementById('password').value = '"+password+"';" +
"var frms = document.getElementsByName('loginForm');" +
"frms[0].submit(); };");
Here is complete code which works for me (Bitbucket):
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.loadUrl("http://example.com/");
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
final String password = "password";
final String username = "username";
final String answer = 5;
final String js = "javascript:" +
"document.getElementById('password').value = '" + password + "';" +
"document.getElementById('username').value = '" + username + "';" +
"var ans = document.getElementsByName('answer');" +
"ans[0].value = '" + answer + "';" +
"document.getElementById('fl').click()";
if (Build.VERSION.SDK_INT >= 19) {
view.evaluateJavascript(js, new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
}
});
} else {
view.loadUrl(js);
}
}
});
I tried #user802467 solution.But there was a different behaviour in 2 things
If I stored ONLY the last javascript call in a variable, it was not filling in the fields. Instead if I stored all the three calls in variables, it did
For some reason my form was not being submitted using submit(). But instead of submitting the form, if I clicked on the submit button using button.click(), I didnot need to store all the three calls and everything worked perfectly!
Here is what I used (but didnt work)
view.loadUrl("javascript: var x = document.getElementById('username').value = '" + username + "';" +
"var y = document.getElementById('password').value = '" + password + "';" +
"var form1 = document.getElementById('loginform');" +
"form1[0].submit(); ");
Here is the code that worked for me
view.loadUrl("javascript: document.getElementById('username').value = '" + username + "';" +
" document.getElementById('password').value = '" + password + "';" +
"var z = document.getElementById('submitbutton').click();"
);
It works for me
webView.loadUrl("javascript:var uselessvar =document.getElementById('regno').value='"+mob+"';",null);
webView.loadUrl("javascript:var uselessvar =document.getElementById('passwd').value='"+pass+"';",null);
Related
I have a webview that I display some html texts (I have them in assets). I'd like to allow users to highlight some parts of it.
I was thinking in some solutions:
try to put the texts user hightlight in a shared pref and use:
webview.findAllAsync(shared_pref_string);
webview.setFindListener(new FindListener() {
#Override
public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
// try to select the texts.
}
});
The problem I see is, user can select one word, like "what", and this code will select all "whats" the text has.
Use javascript:
public static String Highlightscript = " <script language="javascript">" +
"function highlightSelection(){" +
"var userSelection = window.getSelection();" +
"for(var i = 0; i < userSelection.rangeCount; i++)"
+ " highlightRange(userSelection.getRangeAt(i));" +
"}" +
"function highlightRange(range){"+
"span = document.createElement(\"span\");"+
"span.appendChild(range.extractContents());"+
"span.setAttribute(\"style\",\"display:block;background:#ffc570;\");"+
"range.insertNode(span);}"+
"</script> ";
webView.loadUrl("javascript:highlightSelection()");
But this 2 solutions not seems nice to me, any other best way to do this and more modern?
this android library is implemented what you need:
https://github.com/FolioReader/FolioReader-Android
they are using this javascript library https://github.com/timdown/rangy, maybe this will make sense.
I am working an an JavaFX Webbrowser that can autologin to some sites, i know how to set the data to username and password fields but how to i make it execute the login button click?
This is what i got so far:
String email = "document.getElementsByName('email')[0].value='MY_EMAIL';";
String pass = "document.getElementsByName('pass')[0].value='MY_PASSWORD';";
String login = "";
webEngine.executeScript(email);
webEngine.executeScript(pass);
webEngine.executeScript(login);
and this is the javascript code of the button it should click:
<label class="uiButton uiButtonConfirm" id="loginbutton" for="u_0_c"><input value="Aanmelden" tabindex="4" type="submit" id="u_0_c"></label>
this is a concentrated, non-specialized example... uses the dom.w3c.Node.* package
HTMLInputElement element = (HTMLInputElement)myWebView.getEngine().getDocument().getElementsByTagName("input").item(0);
element.click();
Find a way to handle the object you're looking for, and it will work.
I haven't tried that, but it should work. The idea is add jQuery to the loaded page and then to use it to click the button. This post explains how to do this with JS: How Do I Add jQuery To Head With JavaScript? So with Java it should be (I've copied the first answer into a string and executing it with the web engine):
String script = "script = document.createElement('script');\n" +
"\n" +
"script.onload = function() {\n" +
" // jQuery is available now\n" +
"};\n" +
"var head = document.getElementsByTagName(\"head\")[0];\n" +
"\n" +
"script.type = 'text/javascript';\n" +
"script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js';\n" +
"\n" +
"head.appendChild(script);";
webEngine.executeScript(script);
This should be done right when WebView is initialized (via webEngine.getLoadWorker().stateProperty().addListener(...)). Note: jQuery is loaded asynchronously.
Now you should be able to click a button with jQuery:
webEngine.executeScript("$('#buttonId')[0].click()");
This post should help you with debugging JS in a WebView: JAVAFX / WebView / WebEngine FireBugLite or Some other debugger?
Using the "Network Updates API" example at the following link I am able to post network updates with no problem using client.postNetworkUpdate(updateText).
http://code.google.com/p/linkedin-j/wiki/GettingStarted
So posting works great.. However posting an update does not return an "UpdateKey" which is used to retrieve stats for post itself such as comments, likes, etc. Without the UpdateKey I cannot retrieve stats. So what I would like to do is post, then retrieve the last post using the getNetworkUpdates() function, and in that retrieval will be the UpdateKey that I need to use later to retrieve stats. Here's a sample script in Java on how to get network updates, but I need to do this in Coldfusion instead of Java.
Network network = client.getNetworkUpdates(EnumSet.of(NetworkUpdateType.STATUS_UPDATE));
System.out.println("Total updates fetched:" + network.getUpdates().getTotal());
for (Update update : network.getUpdates().getUpdateList()) {
System.out.println("-------------------------------");
System.out.println(update.getUpdateKey() + ":" + update.getUpdateContent().getPerson().getFirstName() + " " + update.getUpdateContent().getPerson().getLastName() + "->" + update.getUpdateContent().getPerson().getCurrentStatus());
if (update.getUpdateComments() != null) {
System.out.println("Total comments fetched:" + update.getUpdateComments().getTotal());
for (UpdateComment comment : update.getUpdateComments().getUpdateCommentList()) {
System.out.println(comment.getPerson().getFirstName() + " " + comment.getPerson().getLastName() + "->" + comment.getComment());
}
}
}
Anyone have any thoughts on how to accomplish this using Coldfusion?
Thanks
I have not used that api, but I am guessing you could use the first two lines to grab the number of updates. Then use the overloaded client.getNetworkUpdates(start, end) method to retrieve the last update and obtain its key.
Totally untested, but something along these lines:
<cfscript>
...
// not sure about accessing the STATUS_UPDATE enum. One of these should work:
// method 1
STATUS_UPDATE = createObject("java", "com.google.code.linkedinapi.client.enumeration.NetworkUpdateType$STATUS_UPDATE");
// method 2
NetworkUpdateType = createObject("java", "com.google.code.linkedinapi.client.enumeration.NetworkUpdateType");
STATUS_UPDATE = NetworkUpdateType.valueOf("STATUS_UPDATE");
enumSet = createObject("java", "java.util.EnumSet");
network = yourClientObject.getNetworkUpdates(enumSet.of(STATUS_UPDATE));
numOfUpdates = network.getUpdates().getTotal();
// Add error handling in case numOfUpdates = 0
result = yourClientObject.getNetworkUpdates(numOfUpdates, numOfUpdates);
lastUpdate = result.getUpdates().getUpdateList().get(0);
key = lastUpdate.getUpdateKey();
</cfscript>
You can also use socialauth library to retrieve updates and post status on linkedin.
http://code.google.com/p/socialauth
I'm using google app engine to do a website that has some messages, i would like to display the message with a name in form of a link that appointed to the person profile. The only problem is that all my webpages are dynamic and printed from the code.
What I first thought of doing was a link that in click it would call a method in the program with the parameter of the clicked name. The method would then receive the paramet of the name, do a query and print the profile in a new webpage. I think this would work fine. The problem and question i have is how do I do the clickable name with method call.
My code to print the text message to the html page now is:
List<Texto> results = (List<Texto>) query.execute(tituloparam);
if (!results.isEmpty())
{
for (Texto e : results)
{
resp.getWriter().println("Titulo:"
+ results.get(0).titulo);
resp.getWriter().println("Nome:<a href='/author?name=" + results.get(0).autor + "'>" + results.get(0).autor + "</a>");
resp.getWriter().println("Data:"
+ results.get(0).data);
resp.getWriter().println("Texto:"
+ results.get(0).texto);
}
}
So the autor would be the clickable object. Can anyone help me?
Edit 1: Thanks to uwe (Thank you) now I have a clickable object. But how do I call a method with the parameter = autor from there?
You need to add a link to it like this:
resp.getWriter().println("Nome:<a href='/author?name=" + results.get(0).autor + "'>" + results.get(0).autor + "</a>");
Then it shows it as link and makes it clickable.
I am designing an emergency response page, which needs to display information across 3 different monitors. The first monitor will gather information about the caller, and then contain 2 links. The first link needs to display a different web page on the 2nd monitor, and the 2nd link needs to display a different web page on the 3rd monitor.
Is this possible?
Thanks for any help
The first link needs to display a different web page on the 2nd monitor, and the 2nd link needs to display a different web page on the 3rd monitor.
While, depending on your operating system, it is possible to control where a window appears, there are much fewer options for doing this using javascript / serverside code over HTTP / browsers.
The only sensible way to achieve this is by configuring the displays to be tiles of a larger display rather than independent screens (for *nix/BSD/Linux, check out xinerama).
The code below saves the size of a window - and would only need some simple changes to support x/y offset and multiple windows - I leave it to you as to how you differentiate between the windows.
A simpler approach would be to just have one huge window with frames whose borders align with the monitors.
if (document.getElementById && !document.all) { // NOT for MSIE
stickySizeOverloadOnload(stickySizeSetWindowSize);
stickySizeOverloadOnresize(stickySizeSaveWindowSize);
}
function stickySizeSaveWindowSize(event)
{
var expiry = new Date();
var path = document.location.pathname;
expiry.setDate(expiry.getDate()+500);
stickySizeSetCookie('windowSize', window.outerWidth + ',' + window.outerHeight, expiry, path);
}
function stickySizeSetWindowSize()
{
var saved=stickySizeGetCookie('windowSize');
var parts=new Array();
if (saved.length) {
parts = saved.split(',');
if ((parts[0]>100) && (parts[1]>100)) {
window.outerWidth=parts[0];
window.outerHeight=parts[1];
} else {
alert("invalid size - '" + saved + "'");
stickySizeDeleteCookie('windowSize');
}
}
}
function stickySizeOverloadOnload(func)
{
var oldhandler=window.onload;
if (typeof window.onload != "function") {
window.onload=func;
} else {
window.onload=function(event) {
oldhandler(event);
func(event);
}
}
}
function stickySizeOverloadOnresize(func)
{
var oldhandler=window.onresize;
if (typeof window.onresize != "function") {
window.onresize=func;
} else {
window.onresize=function(event) {
oldhandler(event);
func(event);
}
}
}
function stickySizeSetCookie(name, value, expires, path, domain, secure) {
var curCookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
document.cookie = curCookie;
}
function stickySizeGetCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
} else
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1)
end = dc.length;
return unescape(dc.substring(begin + prefix.length, end));
}
function stickySizeDeleteCookie(name, path, domain) {
if (stickySizeGetCookie(name)) {
document.cookie = name + "=" +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}
You can open the links in a different window with the attribute target="windowName".
You have to set up the three windows manually, so assign them manually to the three screens. When you open a link again in a window it is still on the same screen.
Have a look at Java: Getting resolutions of one/all available monitors (instead of the whole desktop)?
(The answer discuss the GraphicsEnvironment.getLocalGraphicsEnvironment() call)
If you really want the windows to be locked to a specific monitor, you will need to implement this client side. Here is a link describing how to detect which monitor a window is on in Java, so you can move it to the proper monitor and maximize the window if you desire. Obviously you can implement the rest of the system server side and just display pages inside the windows you have created.