7

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 ? Commented Feb 26, 2020 at 22:31
  • 1
    J2V8 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-j2v8 Commented Mar 9, 2020 at 9:39

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

7 Comments

thank you for your answer. can i load the script somehow without using WebView? (I am trying to avoid using WebView at all)
Yes, there is no webview here at all. I was just showing that with J2V8 it's similar to how a browser works.
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) ");
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.
very minor typo in second comment? should that say "contains the function bar(x,y)"?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.