Hi In my android phonegap app i need to call the javascript method from android code (DroidGap).I have tried the sample code.
Here is my code:
super.loadUrl("file:///android_asset/www/index.html");
super.loadUrl("javascript:onload()");
When i use super.loadUrl("javascript:alert('hai')"); i am getting this alert.But when i use the method "onload" i am getting the error.
Here is my error in logcat:
Uncaught TypeError: Property 'onload' of object [object DOMWindow] is not a function at null:1
Here is my script in index.html:
<script type="text/javascript">
function onload()
{
alert("hai");
}
</script>
I dont know where i am wrong.Please guide me.Thanks in Advance.
Try this one and add this line also
super.setWebChromeClient(new WebChromeClient());
super.loadUrl("file:///android_asset/www/index.html");
After this line call like this onPageFinished
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
webview.loadUrl("javascript:(function() {alert("hai") }
);
}
});
Android can only call the javascript method if an html page is currently loaded in webView
first call
webview.loadUrl("Your html page url");
then call
webView.loadUrl("javascript:hello()");
Try to handle the alert function in the java file, like this :
mWebView.setWebChromeClient(new MyWebChromeClient());
final class MyWebChromeClient extends WebChromeClient {
#Override
public boolean onJsAlert(WebView view,String url,
String message,JsResult result) {
new AlertDialog.Builder(MainActivity.this).
setTitle("Alert").setMessage(message).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
}).create().show();
result.confirm();
return super.onJsConfirm(view,url,message, result);
}
}
I had the same problem when I moved the target javascript function from the main page to an separate .js file. For some reason, the loadUrl() function can't find externally-loaded functions - only the ones in the main page. Once I moved the function back, it immediately started working.
Go figure.
Related
I inject the JavaScript function in override WebViewClient.OnPageFinished
public class MyWebViewClient : WebViewClient
{
public void onPageFinished (WebView view, String url)
{
view.EvaluateJavascript("function fun1(){console.log('this is fun1')}", null);
}
}
I can't call the JavaScript function automatically after page the loaded. I try to use
<script>
window.addEventListener('load', (event) => {
fun1();
});
</script>
But console shows "ReferenceError: fun1 is not defined". I think the 'load' event is fired before the onPageFinished method.
I want to know is there an event fired after onPageFinished, or I can inject the js function in another method in Android WebViewClient
Here is my HTML page codes:
<script>
function native_callback() {
alert("Test")
}
</script>
<button onclick='native.appVersion()'>appVersion</button>
As you can see, there is only one button, and when I click the button, it will call the #JavascriptInterface method appVersion(). What I want to do is to call the javascript function native_callback() in the appVersion() method. Unfortunately, I will catch a java exception.
And Here is part of my java source codes of WebView class:
... // some other codes that not related
getSettings().setJavaScriptEnabled(true);
addJavascriptInterface(new InJavaScriptLocalObj(), "native");
... // some other codes that not related
final class InJavaScriptLocalObj {
#JavascriptInterface
public void appVersion() {
Log.i("JsInterface","Called!")
loadUrl("javascript:native_callback()");
}
}
And, I can catch the exception from web page :
Uncaught Error: Java exception was raised during method invocation -- From line 6 of http://my web page url
Line 6 is <button onclick='native.appVersion()'>appVersion</button>.
BTW, the cods Log.i("JsInterface","Called!") has been called, I can see the log.
What should I do ?
Solution
Actually, it's must be called in another thread but same as your WebView object.
Here is my codes:
web_view.post(new Runnable() {
#Override
public void run() {
web_view.loadUrl("javascript:native_callback()");
}
});
How about using handler ?
I checked it works well in my project.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
loadUrl("javascript:native_callback()");
}
}, 0);
I have created an android WebView, and injected javascript interface using addJavascriptInterface(mObject, "jsinterface"). It works fine until I create an object with same name (jsinterface) in JavaScript using the new operator.
My Java Code:
WebView mWebView = findViewById(R.id.myWebView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new MyWebChromeClient((Activity)mContext));
mWebView.addJavascriptInterface(new testClass(), "jsinterface");
mWebView.loadUrl("UrlToLoad");
testClass.java
public class testClass{
public testClass() {
}
#JavascriptInterface
public String testNativeMethod() {
return "Java method called!!";
}
}
My Java Script Code
test.js
function test(msg){
this.message = msg;
this.testJSMethod = function(){
return this.message;
}
}
alert(jsinterface.testNativeMethod()); // prints Java method called!!
jsinterface= new test("JS method called...");
alert(jsinterface.testJSMethod()); // prints JS method called...
alert(jsinterface.testNativeMethod()); // errors "NPMethod called on non- NPObject"
Problem:
Is this possible for a javascript object to have access to both , i.e javascript methods and native JAVA methods(exposed to it via javascriptinterface) ? Is there any possibility of setting any property to webview OR executing any JS script to get this done?
Think about document in javascript. When you are in a web browser, this is a global object that you have access to at any point. If you make your own new var called document, you are going to have problems accessing the global document.
When you execute this line:
mWebView.addJavascriptInterface(new testClass(), "jsinterface");
you are adding a global object called jsinterface. This is the same situation as document. If you create a var with the same name, it will overwrite the existing global reference.
Once you add a javascript interface to the WebView, you don't need to create a new reference to the interface. addJavascriptInterface has already done that for you.
TRY
You may try to make another object, which will retranslate calls to javascript interface.Implement onPageStarted method in WebViewClient , and inject javascript in onPageStarted method, in the following way.
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted (WebView view, String url, Bitmap favicon){
String jsScript= "javascript:var functions_array = ['testNativeMethod'];";
jsScript+="var jsinterface = {};"
jsScript+="functions_array.map(function(id){"
jsScript+="jsinterface[id]= function() {"
jsScript+="try{return temp_obj[id].apply(temp_obj, arguments);}"
jsScript+="catch(e) { console.log('ERROR: ' + e + ', method ' + id);"
jsScript+="return false;}}})"
view.loadUrl(jsScript);
}
});
Hope this helps :-)
js code like this:
function a(){return "hello";}
in android webview activity, how to call js function a() get the return value "hello" ?
webview.addJavaInterface? webview.loadUrl()? i can`t get it.
please tell me how to solve the problem.
My advice would be:
1- Define a Javascript interface
A plain Java class with some methods and attributes, use annotation to expose the method you desire to the webview JS scope
public class MyInterface {
private WebView webView;
//pass the reference to the webview in your constructor
public JavascriptCallback(WebView webView) {
this.webView = webView;
}
//expose this method to the JS scope using annotation
#JavascriptInterface
void sumNumbers(final String num1, final String num2, final String JScallbackFn) {
this.javascriptCallback(JScallbackFn, num1 + num2);
}
//run the callback into the JS scope
void javascriptCallback(final String callback, final String result) {
webView.post(new Runnable() {
#Override
public void run() { webView.load("javascript:"+callback+"("+result+")", null);
}
});
}
2- Inject the JavaScript interface in your webview
webview.addJavascriptInterface(new MyInterface(this.getActivity(), webview), "MyInterface");
3- Invoke the JS method (from within the webview)
MyInterface.sumNumbers(12, 34, showResult);
function showResult(res) {
document.getElementById('myDiv').innerHTML(res);
}
For more extensive explanation about how webviews works on Android check the official documentation http://developer.android.com/guide/webapps/webview.html
I have a problem: when I use webview with javascript interface to comunication between my activity and the html page, my actionbarsherlock stop working. And the problem is in this line:
myWebView.addJavascriptInterface(new JsObject(), "injectedObject");
the problems include List navigations and menu items with ActionView .
Basically if I comment the above code, everything works normally.
Some pictures to explain:
My Activity with sherlockactionbar and webview
My actionbar not working when when I'm calling the method addJavascriptInterface in my webview
My actionbar working when I remove the method addJavascriptInterface
How can I solve this problem???? Thanks.
Oh, I figured out my problem looking at this question
Basically I had a method accessed by javascript that disguised a view. So this occasioned UI errors.
Before:
class JsObject {
#JavascriptInterface
public void cancelProgress() {
progressbar.setVisibility(View.GONE);
}
}
After:
class JsObject {
#JavascriptInterface
public void cancelProgress() {
runOnUiThread(new Runnable(){
#Override
public void run(){
progressbar.setVisibility(View.GONE);
}
});
}
}