I am using Java Access Bridge API with interop in C#. When trying to create a new AccessibleWindow with the hwnd obtained from the user32.dll method GetForegroundWindow(), it does not recognize the window as a java window, returning null. IsJavaWindow() returns false, but calling it a second time returns true. I tested this out with the example "SwingSet2" application.
public void Initialize()
{
if(!Initialized)
{
accessBridge = new AccessBridge();
var hwnd = WindowsNativeMethods.GetForegroundWindow();
var window = accessBridge.CreateAccessibleWindow(hwnd);
window.AccessBridge.Initialize();
window.AccessBridge.Functions.GetAccessibleContextFromHWND(hwnd, out vmId, out mainContext);
Initialized = true;
}
}
I am also using code from this repo: Google Access Bridge
Initialize() or the initialization code in general needs to called in a UI thread or a message pumping thread.
Using the IntPtr from GetForegroundWindow() or GetActiveWindow() always returns false in IsJavaWindow(), but using FindWindow() works from user32.dll's methods.
I'm trying to develop an extension for firebug. I want to call a java method in this extension but there is no html in it so I can't use the applet-html solution.
Here is my java Applet :
import java.applet.Applet;
import javax.swing.JOptionPane;
public class MyApplet extends Applet {
public void init() {
super.init();
System.out.println("init something");
}
public String jsCall(String hello) {
System.out.println("this method is called by a js function and say :"
+ hello);
Thread t = new Thread(new Runnable(){
public void run(){
JOptionPane jop1 = new JOptionPane();
jop1.showMessageDialog(null, "Message informatif", "Information", JOptionPane.INFORMATION_MESSAGE);
}
});
t.start();
return "lala";
}
}
I try this:
var applet = document.createElement("applet");
applet.setAttribute("code","file:///home/dacostam/z_test/firebug-extension-examples-0bdcf15/helloamd#janodvarko.cz/chrome/content/MyApplet.class");
applet.setAttribute("id","javaToJavascriptApplet");
applet.setAttribute("mayscript","true");
applet.jsCall("HelloWorld"); //jsCall not a function
And this:
var dom = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
dom.appendChild(applet);
dom.javaToJavascriptApplet.jsCall("HelloWorld"); //jsCall not a function
The document is not like usual there is no body or html in it.
Is there an other way to call java in javascript instead of the applet-html solution?
Or is there a way to do it with this method but otherwise?
If you need more information, I'm here.
Thanks.
Edit:
It would be to long to explain you what the program do, just keep in mind that it's inevitably in java, I just need to call a method which take a parameter string and return a string or eventually void.
Edit2:
Sorry I have not thought of that, java needs to run on the client.
If your requirement is to make a call from JavaScript to your Java application, you need to clarify where does your Java app needs to run.
If Java needs to run on the client (same machine as your Firebug), it looks like you are either stuck with an applet or you need to be building a tiny webservice in your Java so you can talk to it through a web API on localhost.
If your Java can sit on a server somewhere, you could talk to your Java application through a web API (similarly to the second option above).
I have code which uses ScriptEngineManager, ScriptEngine class for executing JavaScript code using Java. But it works fine in Java SE, and doesn't work in Android - SDK show error of missing classes. Is it possible to execute JS code in Android? Thank you.
AndroidJSCore is a great one. And here is another little library I wrote for evaluating JavaScript:
https://github.com/evgenyneu/js-evaluator-for-android
jsEvaluator.evaluate("function hello(){ return 'Hello world!'; } hello();", new JsCallback() {
#Override
public void onResult(final String result) {
// get result here (optional)
}
});
It creates a WebView behind the scenes. Works on Android version 3 and newer.
You can use Webview which inherits View class. Make an XML tag and use findViewById() function to use in the activity. But to use the JavaScript, you can make a HTML file containing the JavaScript code. The example blelow might help.
Webview browser=(Webview) findViewById(R.main.browser); //if you gave the id as browser
browser.getSettings().setJavaScriptEnabled(true); //Yes you have to do it
browser.loadUrl("file:///android_asset/JsPage.html"); //If you put the HTML file in asset folder of android
Remember that the JS will run on WebView, not in native environment, thus you might experience a lag or slow FPS in emulator. However when using on an actual phone, the code may run fast, depending on how fast is your phone.
http://divineprogrammer.blogspot.com/2009/11/javascript-rhino-on-android.html will get you started. ScriptEngine is a java thing. Android doesn't have a JVM but a DalvikVM which is not identical but similar.
UPDATE 2018: AndroidJSCore has been superseded by LiquidCore, which is based on V8. Not only does it include the V8 engine, but all of Node.js is available as well.
Original answer:
AndroidJSCore is an Android Java JNI wrapper around Webkit's JavaScriptCore C library. It is inspired by the Objective-C JavaScriptCore Framework included natively in iOS 7. Being able to natively use JavaScript in an app without requiring the use of JavaScript injection on a bloated, slow, security-constrained WebView is very useful for many types of apps, such as games or platforms that support plugins. However, its use is artificially limited because the framework is only supported on iOS. Most developers want to use technologies that will scale across both major mobile operating systems. AndroidJSCore was designed to support that requirement.
For example, you can share Java objects and make async calls:
public interface IAsyncObj {
public void callMeMaybe(Integer ms, JSValue callback) throws JSException;
}
public class AsyncObj extends JSObject implements IAsyncObj {
public AsyncObj(JSContext ctx) throws JSException { super(ctx,IAsyncObj.class); }
#Override
public void callMeMaybe(Integer ms, JSValue callback) throws JSException {
new CallMeLater(ms).execute(callback.toObject());
}
private class CallMeLater extends AsyncTask<JSObject, Void, JSObject> {
public CallMeLater(Integer ms) {
this.ms = ms;
}
private final Integer ms;
#Override
protected JSObject doInBackground(JSObject... params) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.interrupted();
}
return params[0];
}
#Override
protected void onPostExecute(JSObject callback) {
JSValue args [] = { new JSValue(context,
"This is a delayed message from Java!") };
try {
callback.callAsFunction(null, args);
} catch (JSException e) {
System.out.println(e);
}
}
}
}
public void run() throws JSException {
AsyncObj async = new AsyncObj(context);
context.property("async",async);
context.evaluateScript(
"log('Please call me back in 5 seconds');\n" +
"async.callMeMaybe(5000, function(msg) {\n" +
" alert(msg);\n" +
" log('Whoomp. There it is.');\n" +
"});\n" +
"log('async.callMeMaybe() has returned, but wait for it ...');\n"
);
}
I was also looking for a way to run javascript on Android and came across j2v8 library. This is a java wrapper for Google's v8 engine.
To use it add a dependency:
compile 'com.eclipsesource.j2v8:j2v8_android:3.0.5#aar'
It has pretty simple api, but I haven't found any docs online apart from javadoc in maven repository. The articles on their blog are also useful.
Code sample from this article:
public static void main(String[] args) {
V8 runtime = V8.createV8Runtime();
int result = runtime.executeIntegerScript(""
+ "var hello = 'hello, ';\n"
+ "var world = 'world!';\n"
+ "hello.concat(world).length;\n");
System.out.println(result);
runtime.release();
}
The javax.script package is not part of the Android SDK. You can execute JavaScript in a WebView, as described here. You perhaps can use Rhino, as described here. You might also take a look at the Scripting Layer for Android project.
You can use Rhino library to execute JavaScript without WebView.
Download Rhino first, unzip it, put the js.jar file under libs folder. It is very small, so you don't need to worry your apk file will be ridiculously large because of this one external jar.
Here is some simple code to execute JavaScript code.
Object[] params = new Object[] { "javaScriptParam" };
// Every Rhino VM begins with the enter()
// This Context is not Android's Context
Context rhino = Context.enter();
// Turn off optimization to make Rhino Android compatible
rhino.setOptimizationLevel(-1);
try {
Scriptable scope = rhino.initStandardObjects();
// Note the forth argument is 1, which means the JavaScript source has
// been compressed to only one line using something like YUI
rhino.evaluateString(scope, javaScriptCode, "JavaScript", 1, null);
// Get the functionName defined in JavaScriptCode
Object obj = scope.get(functionNameInJavaScriptCode, scope);
if (obj instanceof Function) {
Function jsFunction = (Function) obj;
// Call the function with params
Object jsResult = jsFunction.call(rhino, scope, scope, params);
// Parse the jsResult object to a String
String result = Context.toString(jsResult);
}
} finally {
Context.exit();
}
You can see more details at my post.
Given that ScriptEngineManager and ScriptEngine are part of the JDK and Android SDK is not the same thing as the JDK I would say that you can't use these classes to work with JavaScript under Android.
You can check the Android SDK's reference documentation/package index to see what classes are included (what can you work on Android out of the box) and which of them are missing.
I just found the App JavaScript for Android, which is the Rhino JavaScript engine for Java. It can use all Java-classes, so it has BIG potential. The problem is it might be slow, since it is not really optimized (heavy CPU load). There is another JavaScript engine named Nashorn, but that unfortunately doesn't works on Google's DalvikVM Java engine (does not support the optimizations of Oracle Java engine). I hope Google keeps up with that, I would just love it!
If you want to run some javascript code on chrome browser as per the question copy this code and paste it into address bar:
data:text/html, <html contenteditable> <title> Notepad </title> <script> alert('Abhasker Alert Test on Mobile'); </script> </html>
I have the following code in an applet to call some Javascript (it's a bit convoluted because the fn that's called gets an object from the DOM identified by divId and calls a function on it).
#Override
public final void start() {
System.err.println("start() method called");
this.javascript = JSObject.getWindow(this);
this.jsObjectDivId = getParameter("parent_div_id");
this.initCallbackFnName = getParameter("init_callback");
Object args[] = {this.jsObjectDivId, this.initCallbackFnName};
System.out.print("Calling init_callback\n");
this.javascript.call("callJS", args);
}
The callJS function is:
window.callJS = function(divId, functionName, jsonArgString) {
var args, obj;
obj = $(divId).data('neatObject');
args = eval(jsonArgString);
return obj[functionName](args);
};
In Firefox/Chrome the divId and functionName arguments contain valid strings and everything works fine; the desired function is called on the object hanging off the specified DIV data.
In Safari, the divId and functionName arguments are both reported as a JavaRuntimeObject with values of true.
> divId
JavaRuntimeObject
true
What gives?
LiveConnect is not fully supported in all browsers. Especially, Safari doesn't convert Java Strings to the prober JS equivalent when using call. In your case you can just use eval at the Applet side instead of call and put in a JSON string object with the arguments. Something like:
javascript.eval(callback + "({\"id\":\"" + id + "\",\" ... })")
Basically, you need to know the cross-browser compatible subset of LiveConnect that works.
I've written a blog post that describes the subset: http://blog.aarhusworks.com/applets-missing-information-about-liveconnect-and-deployment/
It comes with a LiveConnect test suite which runs in the browser: http://www.jdams.org/live-connect-test
I had a similar issue with calling a method on an applet in Safari. It was returning a JavaRuntimeObject that I caused an exception when it was user later on.
As pointed out by #edoloughlin I had to use (applet.getMethod() + "") after which point the proper string was evaluated.
The comment saved me a bunch of time so I thought it useful to add here as I can't comment above.
public static native void doConnect() /*-{
$wnd.jQuery(document).trigger('connect',
{
jid: 'sss',
password: 'sss'
}
);
}-*/;
i tried the above ,but there is no error in firebug or gwt hosted mode
console(so i cannot know whether the code is success or not). may i know is this the correct way to call jquery trigger? but when i put alert() in bind('connect'), it was not called
inside .js file
$(document).bind('connect', function (ev, data) {
alert('not call.....at all');
var conn = new Strophe.Connection(
"http://bosh/xmpp-httpbind");
conn.connect(data.jid, data.password, function (status) {
if (status === Strophe.Status.CONNECTED) {
$(document).trigger('connected');
} else if (status === Strophe.Status.DISCONNECTED) {
$(document).trigger('disconnected');
}
});
Hello.connection = conn;
});
I had similar issues when using jQuery UI with GWT - no errors in console/dev mode, yet the code did not behave like I wanted. The reason was that jQuery (and such frameworks) extend/change many core elements of JavaScript and expect it to stay that way - however, GWT code (meaning, also JSNI stuff) is executed from a "clean" iframe (so that no external frameworks can mess with the language and cause some weird errors in GWT, that's why you have to reference to the main window via $wnd).
I'd suggest moving your doConnect function to the host page (or external js file linked to the host page) and instead just call that function from your JSNI stub:
public static native void doConnect() /*-{
$wnd._doConnect('sss','sss'); //_doConnect defined in the host page
}-*/;
Or provide helper functions that will return Arrays, etc, from the host page, so that they include all the changes that jQuery made and expects.
It's a bit late for this answer, but your original code did not work due to a simple mistake: You have properly used $win instead of window but a few characters later you have used document instead of $doc :)
public static native void doConnect() /*-{
$wnd.jQuery($doc).trigger($wnd.jQuery.Event('connect', {
jid: 'sss',
password: 'sss'
}));
}-*/;