Call Javascript function in android webview (Uncaught ReferenceError) - javascript

I am trying to call a javascript function inside a webview. And I keep getting the following error.
[INFO:CONSOLE(1)] "Uncaught ReferenceError: onOTP is not defined", source: (1)
Please you ask, this function is only getting called inside the onPageFinished() method of the webview client. I am successfully able to call an Android function from the html but not the other way around.
Any help?
This is my javascript method:
function onOTP(otp){
console.dir("Otp Triggered " + otp);
}
This javascript code is inside a separate js file. I thought that might be the issue and added the same code to the html page with a script tag and still the same issue.
And I am calling this inside:
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mWebView.loadUrl("javascript:onOTP(465601)");
}
Can someone please let me know what I am doing wrong in this?
Thanks in advance for your help!

Related

Android Webview - Change Elements with Javascript after page finished loading

I want to change some values on a HTML Page, using Javascript in a Webview.
I tried many different ways to evaluate Javscript after page finished loading.
Here is my code:
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setBlockNetworkImage(false);
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
webview.loadUrl("javascript:(function() { document.getElementById('options').value = '" + found.getId() + "'; ;})()");
button.performClick();
}
});
I think it means, that the method is called to early, before page is fully loaded.
Do you have any ideas?
in order to change value / content / styling in HTML using javascript also known as DOM Manipulate, then we have waiting after DOM ready or fully loaded. In this case, we load the page into widget WebView and then do our business.
I have a sample code that I always use in the same case,
...
final String url = "http://example.com";
final WebView webview = findViewById(R.id.my_webview);
final String myNewValue = "it works!";
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(new WebChromeClient());
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
// Your custom javascript here
String myCustomJS = "document.getElementById('options').innerHTML = '" +
myNewValue + "'";
// here we execute the javascript code
webview.loadUrl("javascript:(function(){" + myCustomJS + "})()");
}
});
// and here we load the url
webview.loadUrl(url);
...
I hope the code above can help you to continue working..
Update for Waiting DOM Ready
If you have use jQuery before, then you must know
// example 1: jQuery way
$(document).ready(function() {
// place our logic here
});
// example 2: native javascript way
document.addEventListener('DOMContentLoaded', function() {
// place our logic here
});
Im use this trick to manipulate page in WebView after DOM ready (in example 2 native JS way).
Another question why not using runnable?
because we never know internet speed users, let say if we set runnable to wait 3000ms or 3sec but the web not responding after runnable execution. What happened next? users will have white blank screen and keep waiting.
hope this more clear now.
reference link: https://developer.mozilla.org/.../DOMContentLoaded_event

HTMLUnit: ReferenceError: "$" is not defined

I am trying to login to a website using AjaxForm. I managed to retine the forms and reach the xpath of the desired button though when I call #click I get this error:
EcmaError: lineNumber=[193] column=[0] lineSource=[<no source>] name=[ReferenceError] sourceName=[script in https://test.paypo.com/Account/Login?ReturnUrl=%2FHome%2FStart from (177, 32) to (221, 10)]
message=[ReferenceError: "Paypo" is not defined.
(script in https://test.paypo.com/Account/Login?ReturnUrl=%2FHome%2FStart from (177, 32) to (221, 10)#193)]
com.gargoylesoftware.htmlunit.ScriptException: ReferenceError: "Paypo" is not defined. (script in https://test.paypo.com/Account/Login?ReturnUrl=%2FHome%2FStart from (177, 32) to (221, 10)#193)
I am honestly clueless on how to get around this... important note is that I have no access to the source of the website, the actual website logging works perfectly fine.
I've tried using any kind of BrowserVersion and different HtmlUnit versions...
Current code:
final HtmlPage thePage = ((HtmlPage) page);
final HtmlButtonInput button = (HtmlButtonInput) thePage.getByXPath("//input[#type='button']").get(0);
webClient.getOptions().setThrowExceptionOnScriptError(true);
final HtmlPage newPage = button.click();
Error araises when #click is called!
Any clue? Please!
Ok have done a short check with this code:
final String url = "https://test.paypo.com/Account/Login?ReturnUrl=%2FHome%2FStart";
try (final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_60)) {
HtmlPage page = webClient.getPage(url);
}
Running this produces a bunch of errors; the first one is
com.gargoylesoftware.htmlunit.ScriptException: identifier is a reserved word: class (https://test.paypo.com/bundles/SharedJS?v=qrYYsvxJCv4nRnx8xzi1sMLBQPQlIPteJjoj8eCO1go1#7)
What does this mean?
The page includes some js code from the url https://test.paypo.com/bundles/SharedJS?v=qrYYsvxJCv4nRnx8xzi1sMLBQPQlIPteJjoj8eCO1go1 and there is a problem with this code. In detail the code uses the javascript 'class' language feature and HtmlUnit (in the end Rhino) does not support this syntax in the current version
Because of this the javascript from this external resource is not 'compilable' and thereof not available for the other javascript on that page
And finally this leads to the error you are facing.

How to call html file's javascript function with help of webview?

I am working on xamarin.forms. I am creating an app for android. I have a html file in which a java script function is placed. I placed the html file inside the Assets folder. The java script function returns some value that I need to use in my c# code.
I am using a webview and inside it I load the html file. Then with help of webview.Eval() method I am trying to call the javascript method. But unfortunately this method doesn't return value. It is void type.
Then I tried to use Android.Webkit.Webview and call the webView.EvaluateJavascript(function, new JavascriptResult()); method. But I am getting null value in result.
I am using following code:
Android.Webkit.WebView webView = new Android.Webkit.WebView(GlobalClass.AndroidContext);
webView.Settings.JavaScriptEnabled = true;
webView.LoadUrl("file:///android_asset/Content/RSAGen2.htm");
webView.EvaluateJavascript(function, new JavascriptResult());
public class JavascriptResult : Java.Lang.Object, Android.Webkit.IValueCallback
{
public string Result;
public void OnReceiveValue(Java.Lang.Object result)
{
string json = ((Java.Lang.String)result).ToString();
Result = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(json);
Notify();
}
}
I am getting null value in result.
Can anyone tell me how I can get the value form javascript function with help of webview?
Regards,
Anand Dubey

Android - Javascript: how to execute jquery in webview

I'm building an app which load a webpage in a webview.
In that webpage, i need to programmatically click on some links using Jquery.
Now, i know how to execute a Javascript code on the webview programmatically (see below):
WebSettings myBrowserSettings = myBrowser.getSettings();
myBrowserSettings.setJavaScriptEnabled(true);
Log.d("Stefano", "JS enabled");
myBrowser.loadUrl("javascript:document.getElementsByid('myWord').click();");
But now, I need to know how implement a Jquery function in my webview; i'm looking for the correct way to manage something like:
myBrowser.loadUrl("jquery:function($("#myAnchor").click(function(event){})");
And which is the correct way to implement the following function?
$("#a_link")[0].click();
If jquery loaded in this page, you can just call this:
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
webview.loadUrl("javascript:(function() { " +
"$("#myAnchor").click(function(event){}" +
"})()");
}
});
What's your problem? It's about escaping characters?
myBrowser.loadUrl("jquery:function($(\"#myAnchor\").click(function(event){})");

How do i use JavaScript evaluate() in an Android WebView?

I want to create a calculator which is able to evaluate Strings like 3+(2-1)*2 or (28.4/2-1.5)+(4-2). I searched the web and found the possibility to use a WebView with JavaScript enabled which can evaluate() Strings.
How do i use JavaScript in a WebView?
How can i pass for example input.getText().toString() to the JavaScript and get back a value?
How do i access evaluate() of JavaScript in my Java-code?
I found a tutorial here. I have to load the HTML-file into my WebView, don't i?
You are going right. For using javascript in webview, after you load url to webview,(you can catch to page loading done at onPageFinish function) at onPageFinish function, you call js like this:
But first you must give permission to webview with these code blocks:
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
webview.loadUrl("javascript:setPageHeight("+contentHeight+");"); // you can pass param with call js function at loaded page.
webview.loadUrl("javascript:alert('test');"); // or you can call like this
For take result param from webview with js you must a subclass like this:
class JavaScriptInterface {
public void showToast(String msg) {
Toast.makeText(mContext, "Received Msg :" + msg,Toast.LENGTH_SHORT).show();
}
}
Then you give this to your webview at the define webview lines
webview.addJavascriptInterface(new JavaScriptInterface(), "MyAndroid");
Finally you call java function in your html in js like this:
<html>
<head>
<script type="text/javascript">
function sayHello(msg){
//calls Android's JavaScriptInterface Function
MyAndroid.showToast(msg);
}
</script>
</head>
<body >
<div onclick="sayHello('hello')"> Click Me !! </div>
</body>
</html>

Categories