How to invoke JS function from Android WebView? - javascript

I'm trying to invoke JS method from Android level.
I created #JavascriptInterface. In the method of the WebViewClient class, I injected the JS script with the JS function which is calling Android interface method in Java (I injected it in WebViewClient #Override onPageFinished method)
Now from the JS level (by injecting it) I can run the Android method.
But I want also inform html page to reload by JS script - by changing URL hash (#fragment).
I mean, I want to call from the Android level the JS method of the html page,
specifically javascript: window.location.replace = ... or window.location.hash = ...
Is this even possible?

Related

unable to execute javascript code in Android WebView from Service

I'm attempting to create and Android service that performs a task using JavaScript. I came across this post which describes how to run JavaScript code inside of a WebView within a Service using the WindowManager. I am able to create a WebView with an .html and .js file with no problem. It is once I try to pass data from the android .java service to the WebView that I run into an issue.
I have tried doing so in this fashion:
final WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
...
wv = new WebView(this);
wv.setWebViewClient(new WebViewClient());
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl("file:///android_asset/www/test.html");
windowManager.addView(wv, params); // params set using method from linked post above
wv.evaluateJavascript("console.log('hello');", null);
wv.loadUrl("javascript:console.log('blah')");
Neither the call to evaluateJavascript() nor loadUrl() appear to have any effect on the WebView (I access the console using the chrome developer tools).
I have tested that in test.html I can add a <script> tag and output text to the console with no issue.
I've also tried calling the functions before adding the view to no avail.
What kind of data you want to pass to Javascript? You could use the WebView.addJavascriptInterface() to "Plant" methods on the HTML document so you can call them from Javascript, invoke in native and return data back to Javascript. Will that help?
If you're trying to execute this from a Service, you'll need to post a Runnable on the UI thread. Read the doc for evaluateJavascript()
It explicitly says it must be called on the UI thread. I think you can just do:
wv.post(new Runnable(){
#Override public void run()
{
wv.evaluateJavascript();
}
});
Other than that, should you include tags?

Transferring a javascript variable to to Objective C (IOS)

I am working on creating an app and am a relatively new Objective C programmer. On a page, "test.php", I have a javascript variable. Here is a simplified version.
<script>
var idx = 45;
document.write(idx);
</script>
I would like to be able to view the value of the variable "idx" in my IOS app, which I have created using Xcode. What would be the optimal way to connect to the page, test.php, and transfer my Javascript variable to Objective C so I could use it as part of my IOS App?
Any help would be greatly appreciated. Thank you.
You will need to communicate between the webview and the native code using a combination of two pieces. First, you will need to "trigger" the webview into returning some value by calling stringByEvaluatingJavaScriptFromString: on the webview. When the webview tries to navigate because of the javascript call, you can intercept it on the native side with the WebView's shouldStartLoadWithRequest: method.
For details, see the specifics here Invoke method in objective c code from HTML code using UIWebView
That is only if you need some activity in the webview to trigger the fetch (or notify the native code that the value has been set). If the value is always available via JS, you can simply use stringByEvaluatingJavaScriptFromString: as follows:
NSString *returnvalue = [self.webviewForHtml stringByEvaluatingJavaScriptFromString:#"var idx = "return_value";return idx;"];

Android :How to call Cordova(WebView) loadUrl function

Well i am into a VOIP application development.Below is my architecture.
UI: Uses Cordova with JS functions.
Sencha Touch : HTML5 Framework.
Backend: uses C code(engine).
JNI: Use JNI to call C function and Vice Versa.
Platform: Android.
Now we have a single activity which extends the Cordova.
Cordova:
1)Has an activity which loads a webview.
2)All we call is loadUrl with JS functions
3)JS functions will take JSONArray as data,or just a UI display JS function.
**Right now we call loadUrl in AsyncTask and by creating Handler in broadcastreceiver ,and on runOnUiThread of activity.
We see some lag in UI transitions and ANR's. **
Data is received from non UI thread,Now how do i call loadUrl function?
1) Doc says(Loads the given URL), which means it should be called on UI main thread only?
2) Can i create a Handler in plain java class and call loadUrl in handleMessage function?
3)Create a handler in main activity and call loadUrl in handleMessage?
4)runOnUiThread is best way?
5)If the loadUrl should be called on UI main thread how do achieve the same?
6)What is best way to call loadUrl?
You're doing that in the right way. Try to get the data in the async mode and then assign it in the main thread by using. This might help http://developer.android.com/training/articles/perf-anr.html .

can we call an android activity from Phonegap project?

I'm Developing an android application.
I've created some codings using HTML5 and javascript for android. And created a signature capturing application in Native JAva
I wanted to include the Native Signature capture coding in the HTML5 application. Because the signature capturing in the HTML5 is not working perfect for touch devices.
is it possible to call a native android activity from the HTML5 phonegap android application????
Yes, it is possible.
For doing the same you need to add cordova lib to your android project and moreover create a plugin in android by extending the Plugin class.
The overrided method named execute() is there that you can call from your javascripts.
Remember you need to define the path of the class containing execute folder to the config.xml.
Please visit below for complete guide.
Android Plugin
Any Java Native code call be called without using any plugin as following.
Follow The following Steps.
1) Replace the following code with your existing DroidGap Activity.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init(); // Calling this is necessary to make this work
appView.addJavascriptInterface(this, "MainActivity");
/* "this" points the to the object of the current activity. "MainActivity" is used to refer "this" object in JavaScript as in Step 3. */
super.loadUrl("file:///android_asset/www/index.html");
}
2 Add the custom function in current (this) activity as following.
public void customFunctionCalled() {
Log.e("Custom Function Called", "Custom Function Called");
}
3 Now call this function from your HTML/JavaScript code as following.
<script type="text/javascript">
function callNewActivity() {
window.MainActivity.customFunctionCalled();
}

Android: Calling javascript from WebView

We're coding an app for Android. It's a WebView that contains Html5 pages. We're using loadUrl() webview's method, in order to push some native OS variables to html, such as:
webview.loadUrl("javascript:myJavascriptFunc('" + myAndroidOSVar + "');");
It works pretty fine. But if we are typing on an input from page while loadUrl() is called, we lose focus of our input fields, even if javascript function called just changes a flag on cache.
Do you know other way to call a Javascript function from WebView instead of loadUrl()?
This is the closest you can get to avoiding the issue: WebView hides soft keyboard during loadUrl(), which means a keyboard cannot stay open while calling javascript
Basically you are avoiding the loadUrl call by queuing up commands on the native side and at an interval letting the JS bridge get the commands and execute using JS eval() or something.
I'm not sure exactly how it will respond if you have multiple fields in the webview, but I came up with a workaround to keep the keyboard shown: https://stackoverflow.com/a/18776064/513038. It may be worth trying.
yes, there is a way by adding a JavaScriptInterface to your WebView , refer this tutorial for more explanation and details

Categories

Resources