I am using J2V8 for execute JavaScript code on Android. In my Java code, can I access and execute JavaScript functions of a separate .js file? If it is possible, how can I do that?
Asked
Active
Viewed 3,476 times
7
-
How did you install J2V8 in your android project ? – pnizzle Feb 26 '20 at 22:31
-
1J2V8 is available in Maven Central. The most recent version is 2.2.1. It can be used in your pom.xml to depend on J2V8. Tutorial: https://eclipsesource.com/blogs/tutorials/getting-started-with-j2v8/ – konbernu Mar 09 '20 at 09:39
1 Answers
7
Like with many JavaScript environments, you simply load the script that contains the other functions you wish to execute browser example. Any functions that are added to the global scope, are now available to you:
V8 v8 = V8.createV8Runtime();
v8.executeScript(readFileAsString("script1")); // contains the function foo();
v8.executeScript(readFileAsString("script2")); // contains the function bar(x, y);
v8.executeJSFunction("foo");
v8.executeJSFunction("bar", 7, 8);
-
1thank you for your answer. can i load the script somehow without using WebView? (I am trying to avoid using WebView at all) – konbernu Aug 11 '16 at 14:27
-
Yes, there is no webview here at all. I was just showing that with J2V8 it's similar to how a browser works. – irbull Aug 11 '16 at 17:33
-
21. if my function returns an Object, can I get it like this? JSObject testObject = v8.executeJSFunction("testfunction", alfa, beta); 2. once these functions added to the global scope, can i use them in my script? i mean like this: runtime.executeVoidScript("var testObject =testfunction(alfa, beta) "); – konbernu Aug 19 '16 at 14:00
-
1Yes, it will return a V8Object. You need to call `release()` on this object since it holds a native handle. Re: #2, yes, you can call these in your script just like you did. – irbull Aug 19 '16 at 15:00
-
very minor typo in second comment? should that say "contains the function bar(x,y)"? – Jesse Dec 13 '16 at 16:48
-
Thanks Jesse. Fixed it. I move back and forth between foo / bar and simple math examples too often :) – irbull Dec 13 '16 at 23:49
-
Im having issues finding how to install J2V8 in my android project. Any guidelines please? – pnizzle Feb 26 '20 at 22:32