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>
Related
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!
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
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){})");
I have a WebView containing HTML data. The data is generated at runtime. A main feature of my app is highlighting certain parts of this HTML data. I tried this by using javascript.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_reader_page, container, false);
webview = (WebView) rootView.findViewById(R.id.resultText);
webview.getSettings().setJavaScriptEnabled(true);
String page = makeHTML();
webview.loadUrl("file:///android_asset/jquery-1.8.2.js");
webview.loadUrl("file:///android_asset/src_javascript.js");
webview.loadData(page, "text/html", "UTF-8");
return rootView;
}
private String makeHTML() {
StringBuilder sb = new StringBuilder();
sb.append("<!DOCTYPE html>\n");
sb.append("<html>\n");
sb.append("<head>\n");
sb.append("</head>\n");
sb.append("<body>\n");
sb.append(tokenizedText + "\n");
sb.append("</body>\n");
sb.append("</html>\n");
return sb.toString();
}
tokenizedText is my at runtime generated data with this format:
<YT_SEN id="_YT_SEN_0">This is my first sentence.</YT_SEN>
<YT_SEN id="_YT_SEN_1">This is my second sentence.</YT_SEN>
...
When my data is loaded in the WebView, the user can highlight a particular sentence by giving its number. This method then calls the corresponding javascript function:
public void highlightSentence(int sent_id) {
if (android.os.Build.VERSION.SDK_INT < 19) {
webview.loadUrl("javascript:highlightSentence('_YT_SEN_" +sent_id+ "', " +color+ ")");
} else {
webview.evaluateJavascript("javascript:highlightSentence('_YT_SEN_" +sent_id+ "', " +color+ ")", null);
}
}
The javascript function for highlighting (defined inside file:///android_asset/src_javascript.js):
function highlightSentence(object,color)
{
document.getElementById(object).style.backgroundColor = color;
}
The output of Logcat when I execute the highlightSentence method:
I/chromium﹕ [INFO:CONSOLE(1)] "Uncaught ReferenceError: highlightSentence is not defined", source: (1)
Somehow the WebView can't find the highlightSentence function. I think it's because of the way I load the Javascript and JQuery files. Yet I don't know (and can't find) the proper way to load external js-files within at runtime generated HTML data.
Note: I use the WebView solely for offline use, I have no need for any internet communication whatsoever. WebView seemed like the easiest way to enable dynamic highlighting.
It seems the Javascript same origin policy is the root of the problem. The WebView will only load javascript files which are from the same origin as the html. Since no origin for the html was given, the data scheme is used as default. If, however, the data is loaded with the same base url as the javascript files, no problem arises.
Load the html data (with file:///android_asset/javascript/ being the directory of the javascript files):
webview.loadDataWithBaseURL("file:///android_asset/javascript/", page, "text/html", "UTF-8", null);
Then reference the javascript files like this inside the html:
<script src='jquery-1.8.2.js' type='text/javascript'></script>
<script src='src_javascript.js' type='text/javascript'></script>
Assuming your javascript is in the assets directory point to it with a file url
file://android_asset/<some java script file in assets>
file://android_asset/ points to the assets directory in your apk.
So you can reference the script in your html when you build it for the webview.
<script charset='utf-8' type='text/javascript'
src='file://android_asset/myjavascript.js'></script>
I have problem with downloading files in Firefox. I tried to find solution in old posts but I didn't find anything. I understand that solution is very simple, but I think today is not my lucky day :)
Simple example. I try to call a web method from JavaScript and download a file.
Client code:
<script language="javascript" type="text/javascript">
function Test() {
PageMethods.Test(onCompleted);
}
function onCompleted(result) {
window.open(result);
}
</script>
........
<asp:ScriptManager ID="ScriptManager" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<div>
<input type=button value="Download" onclick="Test()"/>
</div>
Server side:
[System.Web.Services.WebMethod]
public static string Test()
{
return "\\Files\\test.zip";
}
Folder 'Files' lies in root folder of Web application.
For IE and Chrome, this code is working fine, and I can download the file. But in Firefox, I get an error:
Server Error in '/' Application.
HTTP Error 400 - Bad Request.
and in url I can see for example:
http://localhost:1406/\Files\test.zip
How can I return the correct path to zip file?
URL don´t allow for backslashes.
If the file is located at \Files\test.zip on your windows webserver root the correct url to the file is http:///Files/test.zip
Change the server side code to:
[System.Web.Services.WebMethod]
public static string Test()
{
return "/Files/test.zip";
}
Web URLs should use forward-slashes instead of backslashes.
In general you should use ResolveUrl method of the System.Web.UI.Control class. But in case of static method there is some workaround solutions.
Replacing the following lines
[System.Web.Services.WebMethod]
public static string Test()
{
return "\\Files\\test.zip";
}
with these might work...
[System.Web.Services.WebMethod]
public static string Test()
{
return "\\\\Files\\test.zip";
}