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?
2
-
How did you install J2V8 in your android project ?pnizzle– pnizzle2020-02-26 22:31:19 +00:00Commented Feb 26, 2020 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: eclipsesource.com/blogs/tutorials/getting-started-with-j2v8konbernu– konbernu2020-03-09 09:39:49 +00:00Commented Mar 9, 2020 at 9:39
Add a comment
|
1 Answer
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);
7 Comments
konbernu
thank you for your answer. can i load the script somehow without using WebView? (I am trying to avoid using WebView at all)
irbull
Yes, there is no webview here at all. I was just showing that with J2V8 it's similar to how a browser works.
konbernu
1. 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) ");
irbull
Yes, 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.Jesse
very minor typo in second comment? should that say "contains the function bar(x,y)"?
|