Code Monkey home page Code Monkey logo

androidjscore's People

Contributors

ericwlange avatar simonexmachina avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

androidjscore's Issues

How to debug JS

I have a large JavaScript file, is there a way to debug like JavaScriptCore in iOS?

UnsatisfiedLinkError couldn't find "libJavaScriptCoreWrapper.so"

As per your instructions I extracted the tarball into the root of my Android project, but the jar file wasn't being loaded so I moved the contents of the lib directory into app/lib and this fixed the problem.

However I now have another error when I try to run my project:

12-23 00:03:03.268 3216-3216/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: be.wades.rhinotest, PID: 3216
java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/be.wades.rhinotest-2/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]] couldn't find "libJavaScriptCoreWrapper.so"
  at java.lang.Runtime.loadLibrary(Runtime.java:366)
  at java.lang.System.loadLibrary(System.java:988)
  at org.liquidplayer.webkit.javascriptcore.JSContext.<clinit>(JSContext.java:205)
  at be.wades.rhinotest.MainActivity.onCreate(MainActivity.java:41)
  at android.app.Activity.performCreate(Activity.java:5990)
  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
  at android.app.ActivityThread.access$800(ActivityThread.java:151)
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
  at android.os.Handler.dispatchMessage(Handler.java:102)
  at android.os.Looper.loop(Looper.java:135)
  at android.app.ActivityThread.main(ActivityThread.java:5257)
  at java.lang.reflect.Method.invoke(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:372)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

This is a blank new project created with Android Studio 1.5. I've tried moving the directories in app/lib into lib as well, but this doesn't fix the problem. Any suggestions?

How to call a JavaScript function

Sorry if I'm being dense, but how do I call a JavaScript function on an JavaScript object? Do I need to assign it to a global variable and use evaluateScript()?

TypeError: undefined is not an object (evaluating 'Array.prototype')

TypeError: undefined is not an object (evaluating 'Array.prototype')
                                                                  at org.liquidplayer.webkit.javascriptcore.JSContext.evaluateScript(JSContext.java:267)
                                                                  at org.liquidplayer.webkit.javascriptcore.JSContext.evaluateScript(JSContext.java:290)
                                                                  at com.i7play.rts.activity.SplashActivity$initData$2.run(SplashActivity.kt:54)
                                                                  at android.os.Handler.handleCallback(Handler.java:751)
                                                                  at android.os.Handler.dispatchMessage(Handler.java:95)

here is my js file:

tags.forEach(function(tag) {
  Node.prototype[tag] = function _tagMethod() {
    var state = this._baseState;
    var args = Array.prototype.slice.call(arguments);

    assert(state.tag === null);
    state.tag = tag;

    this._useArgs(args);

    return this;
  };
});

Can get the JSContext from WebView?

Can get the JSContext from WebView like this:
self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

Call Java functions 10000 times from JS

Hi, thanks for your work, it helps me a lot.

As the code shows, func() is called from JS for 10000 times. It spends about 380ms on Genymotion and about 1200ms on my phone, which seems a little bit long. Did i do something wrong? Does time are spend on java reflection?

Another Problem: If func() is called 50000 times or a lager number, the first start of TestActivity is ok, but the second start will make the app busy and ANR at new JSContext().

JS code:

for (var i = 0; i < 10000; i++) {
    func(i)
}

Java code in TestActivity.onCreate:

mJsContext = new JSContext();
mJsContext.property("func", new JSFunction(mJsContext, "func") {
    public void func(int i) {
    }
});

long start = System.currentTimeMillis();
mJsContext.evaluateScript(js);
long end = System.currentTimeMillis();
long time = end - start;

add to gradle

it there a way to gadle download the androidjscore files automatic like in other libraries with a line like

dependencies {

compile 'com.github.ericwlange:androidjscore:2.1'
}

i have see other projects that are easier to add

x86 and MIPS

could you add x86 and MIPS in your build release?

thanks

How to extends new class ?

Now ,I have a class extends from JSObject,
`interface MzObjectClass {

public void _MzObjectClass(Integer x, String y) throws JSException;
public void func1(Integer a);
public void func2(Integer b, Integer c)  throws JSException;

}

public class MzObject extends JSObject implements MzObjectClass {

public MzObject(JSContext ctx) throws JSException {
    super(ctx, MzObjectClass.class, MzObject.class); // This constructor!;
    System.out.println("MzObject init1");
}
public MzObject(long objRef, JSContext ctx){
    super(objRef, ctx);
    System.out.println("MzObject init2");
}

@Override
public void _MzObjectClass(Integer x, String y)  throws JSException{
    property("x", x);
    property("y", y);
    System.out.println("MzObject init3");
}

@Override
public void func1(Integer a) {
    System.out.println(a);
}
@Override
public void func2(Integer b, Integer c)  throws JSException{
    Integer out = b + c + property("x").toNumber().intValue();
    System.out.println(out);
}

}`

If I want create a new class extends from MzObjetc,HOW?

Support of API < 19

Is this constraint critical? It would be great to use library with API >= 9.
I tried to override minSdkVersion, but on API 9 my app crashes with error "Caused by: java.lang.UnsatisfiedLinkError: Cannot load library: reloc_library[1311]: 798 cannot locate ' log2'..." that seemed to be fixed in your fork of WebView ericwlange/webkit@9c5abf1, but maybe it's wasn't included in version 2.0.

array in JSObject

i hava a JSObject with a method that return ArrayList<HashMap<String, String>>
but when i call it i get a undefined type
also tried to retur a object [] and get the same error, in ios i can return from a function a nsdictionary or a nsarray with no problem

does androidjscore can handle array or object [] for a JSValue?

Build issue

$ hemroid install javascriptcore
WARNING: make-standalone-toolchain.sh will be removed in r13. Please try make_standalone_toolchain.py now to make sure it works for your needs.
HOST_OS=darwin
HOST_EXE=
HOST_ARCH=x86_64
HOST_TAG=darwin-x86_64
HOST_NUM_CPUS=8
BUILD_NUM_CPUS=16
ERROR: Unknown option '--system'. See --help for usage.
Can't build toolchain for armeabi

I am trying to build to library to hopefully help in debugging a hang in the 2.2 pre release and the build steps don't work for me. Let me know what info is helpful or if there is anything I am missing.

Multiple JS Calls in multiple context

Hi,

I am getting the following error on performing multiple js method calls in multiple context
Any idea why this error is coming?

Thanks ,
Ayush Nawani

E/AndroidRuntime: FATAL EXCEPTION: FinalizerWatchdogDaemon
java.util.concurrent.TimeoutException: org.liquidplayer.webkit.javascriptcore.JSObject.finalize() timed out after 10 seconds
                                                                  at org.liquidplayer.webkit.javascriptcore.JSContext$JSContextWorker$SyncRunnable.block(JSContext.java:100)
                                                                  at org.liquidplayer.webkit.javascriptcore.JSContext$JSContextWorker.sync(JSContext.java:113)
                                                                  at org.liquidplayer.webkit.javascriptcore.JSContext.sync(JSContext.java:124)
                                                                  at org.liquidplayer.webkit.javascriptcore.JSObject.finalize(JSObject.java:312)
                                                                  at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:202)
                                                                  at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:185)
                                                                  at java.lang.Thread.run(Thread.java:818)

Babel polyfill.js

Hi,
Babel polyfill.js evaluation causes an infinite run loop on android.
I'm trying to locate the native jni code in your project.
Where is?

Tnx for your work!

few questions

Hi

Thank you for the library, it is really useful!

When are you planning to fix the 2.1 version?
and are you planning to upload the library to remote repository?

Thanks

Problem with android:supportsRtl="true"

Hi,

I was trying out your nice project, but it seems there is one little problem during the AndroidManifest.xml merge process.

Is there any reason why you set android:supportsRtl="true" in your AndroidManifest.xml file? That leads to some merge conflicts that I cannot solve, event not with tools:replace or simiar statements.

Thanks :)

Maybe following thread could be interesting in this case

https://android.jlelse.eu/2-lines-in-manifest-to-remove-when-sharing-your-android-library-565d4c4af04a#.h1przxgye

Is there support for reading/saving files?

Is there support for using some apis such as FileReader or Uint8Array, or any way to efficiently process potentially large files?

I'm having trouble figuring out which APIs are browser specific and which ones are available to this library.

Duplicate libgnustl_shared.so error in 2.2-pre1-release

Hi,
I have a conflict with the 2.2 pre-release:

Error:Execution failed for task ':app:transformNative_libsWithMergeJniLibsForDebug'.

com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK lib/armeabi-v7a/libgnustl_shared.so
File1: app/build/intermediates/exploded-aar/AndroidJSCore-2.2-pre1-release/jni
File2: app/build/intermediates/exploded-aar/MyApp/MyModule/unspecified/jni

I don't know if it is MyModule version of libgnustl_shared.so that is misplaced (I didn't write it) or AndroidJSCore-2.2 version of it but I had no problem with AndroidJSCore-2.1.

Ubuntu 14.04, Android Studio 2.1

JavaScript Syntax error

Hi, I have a large js file(which I use for iOS JavaScriptCore without any issue) to load into JSContext, and it throws JSException like "unexpected script end". There is no more information I can find such as which line and what exactly is missing.

Running a 20k lines JS file make app no response

I ran a 20k lines JS file like below. It made the app no response, or sometimes the first run is well.

var string;
var x;
var mycars = new Array();
mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

...

Activity code:

JSContext context;
long time =  0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    context = new JSContext();
}

public void toRunJS(View view) {
    String js = getFromAssets("test.js");
    context.evaluateScript(js);
    context.garbageCollect();
}

and Layout code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.lht.jscoredemo.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="RunJs"
        android:onClick="toRunJS"/>
</RelativeLayout>

Actually I want to run a 30k lines JS library and it's more complex than this, so I beg for your help.

Patch for 2.1?

Many thanks for this project – we've found it really useful.

In the README, it says: "There is a bug in version 2.1 that causes the app to hang. Working on a patch."

We tried to update one of our apps to 2.1, and we confirm the hang!

Any idea when you might have a patch ready?

Alternatively, is there any progress you could share that might help us fix this? We are going to need this fixed one way or the other in the next week or two, and any help would be appreciated.

Potential build issue

The package is set to "org.liquidplayer.hemroidlib" instead of "org.liquidplayer.webkit.javascriptcore" in the AndroidMainfest.xml file. Is this intentional? I had to modify the project, which I did by exploding the .aar and extracting the hemroid.jar file - this worked fine, but on some phones I got runtime exceptions of the form:

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexException: Multiple dex files define Lorg/liquidplayer/hemroidlib/BuildConfig;

The project was able to compile and run correctly only when I changed the package name to "org.liquidplayer.webkit.javascriptcore".

Create new JSContext makes application busy forever

I'm using this library to make a React Native module, when I try to create a JSContext instance, the whole application just hanged.

I looks like the process stopped after executes the constructor

new JSContext();

I've tried to put the line into a thread, but it still happens. Is there any suggestion on this ?

Many thanks.

LOCAL_SHARED_LIBRARIES := JavaScriptCore_shared

Hello

Super example of course , i just dont understand where is located the source code of the library called
LOCAL_SHARED_LIBRARIES := JavaScriptCore_shared

may you tell me?

Kind regards
david

Unable to execute JavaScript file (Webpack and Babel transpiled)

Hi,
I was using your AndroidJSCExample project to execute javascript file but I am not able to execute it . This javascript file is transpiled using Webpack + Babel . The execution is getting stuck at loading webpack modules in javascript file. It is not even throwing any exception in JSExecptionHandler.

This same javascript file is getting executed without errors in chrome browser and in XCode iOS JavaScriptCore .

I have attached the project files. For my purpose ,I have done modifications in MainActivity.java only and assets folder contains the javascript file.

I am not sure whether this issue is related to issue #14 ?

Thanks

projfiles.zip

App crashes when trying to pass a Java callback

I'm trying to pass a java object for the JS to use as a callback, but when called the app crashes with:
Abort message: 'art/runtime/java_vm_ext.cc:410] JNI DETECTED ERROR IN APPLICATION: JNI SetLongField called with pending exception java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object[] org.liquidplayer.webkit.javascriptcore.JSBaseArray.toArray(java.lang.Class)' on a null object reference'

Java call:

JSFunction func = jsContext.property("callbackTest").toFunction();
        NetworkCallback callback = new NetworkCallback(jsContext) {
            @Override
            public void onSuccess(Object... args) {
                if(null != args[0]) {
                    Log.d(TAG, args[0].toString());
                }
            }

            @Override
            public void onError(Object... args) {
                Log.e(TAG, args[0].toString());
            }
        };

        func.call(null, callback);

JS:

function callbackTest(callback) {
    console.log('Callback Test');//I mapped this to Android Log it works
    callback.onSuccess("Hurray");//this is where the exception happens
}

I have NetworkCallback extending JSObject and implementing an interface. It is declared as abstract. Is this possibly the issue?

If this isn't possible is there a preferred method to get values back to Java after an asynchronous event in Javascript?

Optimizing library

Hi, thank a lot for AndroidJSCore. it is so fast. i test it,
but i wanna optimize native library,
because i create a sample and size of my apk is 42 mg, i wanna decrease it.
can i ?

Best way to tell if a JSValue contains a JSArray

Hi Eric,

Thanks for this library - it's super helpful!

I'm generating an array of arbitrary types in Javascript that I want to handle on a type-by-type basis in Java. JSValue appears to support reflection methods for identifying undefined, null, boolean, number, string and Object, but not for Array. Is there a good way to identify an Array?

For the moment, I'm considering using JSValues isInstanceOfConstructor with Array.constructor as the argument, but I need to get the result of Array.constructor in Java first and that is extra bookkeeping that I'd rather avoid. I also haven't tested if it works :)

Thanks in advance!
Colin

Work around for JSObject slowness... JSON strings?

I am attempting to use this library to load a medium amount of data (a list of some hundred objects) into memory and have found a significant slowness with setting properties for JSObjects.

I see roughly 1 ms per property setting, which doesn't sound like much, but when you are sending a list of over 700 objects with 5 integer properties each, it take upwards of 2 seconds to load into memory.

I found a similar slowness when working with reading properties out of JSObjects and I've noticed that I can process data a lot faster when reading out of JSValues using the toJson() method which uses NDK to process the data. From there I let Android's much faster JSONObject class to take over loading values into primitives for me.

I suspect I might see a similar performance boost if I can load data back into the JS engine using a nonexistant fromJson method. I see a C++ hook in JSValue.java (i.e. makeFromJSONString) that looks like it might be able to convert to JSValues from a JSON string. Are there any plans to connect this soon?

Multithreading and deadlock

there are some deadlooks in the code

if i map a native async methhod with a js callback as parameter
native method call js callback
callback call another async native method
native method call js callback
callback call another async native method

deadlock is some cases

everything is executed in non ui-thread

How to access a nested JSValue?

Hi I am trying to translate the following Objective-c code into Android code:

        JSValue *func = context[@"module"][@"func"];
        JSValue *val = [func callWithArguments:@[arg1, arg2]];

The problem I'm having is the first line. I have looked at all the examples and even looked into the code but couldn't figure out how to access a nested attribute (In this case contest[@"module"][@"func"]).

If it was just a single level attribute I could do JSValue func = context.property("module") but I don't know how to get the func in this particular case.

Sorry if this is a newbie question, but I think others may run into this question as well so thought I would ask!

JSCORE In Unit Test, Cant insatiate JSContext java.lang.UnsatisfiedLinkError: no gnustl_shared in java.library.path

Hi

I am using the AndroidJsCore aar put it in our lib directory and almost everything works great. The problem is that while trying to insatiate the JSCore engine in unit tests using junit 4 we get the error below.

java.lang.UnsatisfiedLinkError: no gnustl_shared in java.library.path

It looks like in a unit test context in Android Studio when the unit tests are running this shared lib can't be loaded. The error is being encountered when we try to create a new JSContext

public static void createEngine(String string)
{
engine = new JSContext(); -------------------> Error Here
exportedItems = new JSObject(engine);
setUpMethods();
engine.evaluateScript(string);
}

JsCore works find when we use it in a app deployed on a phone it just has problems when we try to insatiate it in a Unit Test context in android studio. Have you encountered these issues before using JSCore in unit tests?

I get unknown error issue about Thread

When I try to use new JSContext object, I get the Unknown Error Exception message, and I fix it by put all code into other thread to run, Have you get any kind of this issue?

My env is Android 4.3 on SAMSUNG SCH-N719

Can't find variable: module

Hi. i cannot use function encode & decode in qpaysecure.js

try {
            content = IOUtils
                    .toString(context.getResources().openRawResource(R.raw.qpaysecure)
                            , Charset.forName("UTF-8"));
            jsContext.evaluateScript(content); //error Can't find variable: module
            encodeFn = jsContext.property("encode(royle,1234)");
            String result = encodeFn.toString();
            Log.e("result", result);

        } catch (IOException e) {
            e.printStackTrace();
        }

Error or trying to build arm64 JSC

I was trying to use the AndroidJSCore project to build arm64-v8a JSC with JIT enabled. However, I keep getting this error: "Can't extract gcc patch for arm64-v8a" as it is unable to unpack the gcc-arm64-linux-x86_64.tar.bz2 file located in AndroidJSCore/dist. The exact error I get is:
/bin/tar: This does not look like a tar archive bzip2: (stdin) is not a bzip2 file. /bin/tar: Child returned status 2 /bin/tar: Error is not recoverable: exiting now ERROR: Can't extract gcc patch for arm64-v8a

I tried extracting the file manually but I get the same error. Would you know how to resolve this?
Also would you have any insight on how to get JIT working for armeabi-v7a. I would prefer that but am resorting to 64 bit as it crashes on launch.

ExceptionHandler AndroidJSCore

in ios you can write

JSContext* context = [[JSContext alloc] initWithVirtualMachine:[[JSVirtualMachine alloc] init]];
[ context setExceptionHandler:^(JSContext *context, JSValue *value) {
NSLog(@"%@", value);
}];

it there a way to have ExceptionHandler in android

question : async

is it running in the background? if not can it run in asynctask?

thanks and great job

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.