Skip to content

hackware1993/quickjs-android-wrapper

 
 

Repository files navigation

QuickJS For Android

QuickJS wrapper for Android.

Feature

  • Java types are supported with JavaScript
  • Support promise execute
  • Compile bytecode
  • ESModule (import, export)
  • console.log implement
  • JavaScript exception handler

Download

repositories {
  mavenCentral()
}
        
dependencies {
  implementation 'wang.harlon.quickjs:wrapper:latest.version'
}

See here for the latest version

Usage

Create QuickJSContext

QuickJSContext context = QuickJSContext.create();

Evaluating JavaScript

QuickJSContext context = QuickJSContext.create();
context.evaluate("var a = 1 + 2;");

Supported Java Types

Currently, the following Java types are supported with JavaScript:

  • boolean
  • int when calling JavaScript from Java.
  • double
  • String
  • null
  • JSObject represents a JavaScript object
  • JSFunction represents a JavaScript function
  • JSArray represents a JavaScript Array

Set Property

Java

JSObject globalObj = context.getGlobalObject();
JSObject obj1 = context.createNewJSObject();
obj1.setProperty("stringProperty", "hello");
obj1.setProperty("intProperty", 1);
obj1.setProperty("doubleProperty", 0.1);
obj1.setProperty("booleanProperty", true);
obj1.setProperty("functionProperty", (JSCallFunction) args -> {
    return args[0] + "Wang";
});
globalObj.setProperty("obj1", obj1);

JavaScript

obj1.stringProperty; // hello string
obj1.intProperty; // 1
obj1.doubleProperty; // 0.1
obj1.booleanProperty; // true
obj1.functionProperty('Harlon'); // HarlonWang

Get Property

JavaScript

var obj1 = {
	stringProperty: 'hello string',
	intProperety: 1,
	doubleProperty: 0.1,
	booleanProperty: true,
	functionProperty: (name) => { return name + 'Wang'; }
}

Java

JSObject globalObject = context.getGlobalObject();
JSObject obj1 = globalObject.getJSObjectProperty("obj1");
obj1.getProperty("stringProperty"); // hello
obj1.getProperty("intProperty"); // 1
obj1.getProperty("doubleProperty"); // 0.1
obj1.getProperty("booleanProperty"); // true
obj1.getJSFunctionProperty("functionProperty").call("Harlon"); // HarlonWang

Compile ByteCode

byte[] code = context.compile("'hello, world!'.toUpperCase();");
context.execute(code);

ESModule

Java

JSModule.setModuleLoader(new JSModule.Loader() {
    @Override
    public String getModuleScript(String moduleName) {
        return "export var name = 'Hello world';\n" +
                "export var age = 18;";
    }
});

JavaScript

import {name, age} from './a.js';

console.log('name:' + name); // Jack
console.log('age:' + age); // 18

Concurrency

JavaScript runtimes are single threaded. All execution in the JavaScript runtime is guaranteed thread safe, by way of Java synchronization.

Reference

About

QuickJS wrapper for Android

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • C 96.6%
  • Java 1.8%
  • C++ 1.5%
  • CMake 0.1%