Scripto


Source link: https://github.com/ImangazalievM/Scripto

Scripto

??????? ?????? (Russian version)

Library for easy call JS-functions from Java.

Setup

compile 'com.github.imangazalievm:scripto:2.0.1'

Using the library

Calling JS-functions from Java

We have a JS-file with some functions:

function setLogin(login) {

  document.getElementById('login_field').value = login; 
}
  function getLogin() {

  return document.getElementById('login_field').value; 
}

To call a function we should create Java-interface with JS-functions description:

public interface LoginScript {

JavaScriptFunctionCall<Void> setLogin(String login);

JavaScriptFunctionCall<String> getLogin();
  
}

Methods should be return JavaScriptFunctionCall. In the parameters of JavaScriptFunctionCall we specify type of JS-function response. In our case the first function returns nothing (Void), and the second returns text (String).

Then we should link Java-interface and JS-file:

WebView webView = ...; Scripto scripto = new Scripto.Builder(webView).build();
 LoginScript loginScript = scripto.create(LoginScript.class);

Scripts should be linked to interfaces before the page is loaded.

We can't use our script, because we need to wait for full page load. For this we need to set a listener:

scripto.onPrepared(new ScriptoPrepareListener() {

  @Override
  public void onScriptoPrepared() {

 loginScript.setLogin("MySuperLogin").call();

  
}
 
}
);

To obtain data from a function use the following syntax:

loginScript.getLogin()
  .onResponse(login -> Toast.makeText(MainActivity.this, login, Toast.LENGTH_LONG).show())
  .call();

Also we can handle errors, caused in JS-code:

.onError(error -> Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show())

For the conversion of user-defined data type from JSON used GSON library.

If you want to get raw JSON, then necessarily to use class RawReponse:

JavaScriptFunctionCall<RawResponse> getJson();

Receiving JSON:

loginScript.getJson()
  .onResponse(response -> Toast.makeText(MainActivity.this, response.getResponse(), Toast.LENGTH_LONG).show())
  .call();

Calling Java-methods from JavaScript

Calling Java-methods from JavaScript very similar to default JavaScriptInterface. Create Java-class, which will act as JS-inteface:

public class AndroidInterface {

private Context context;

public AndroidInterface(Context context) {

this.context = context;
  
}

public void showToastMessage(String text) {

Toast.makeText(context, text, Toast.LENGTH_SHORT).show();

  
}
 
}

For correct work of JS-interface must not contain methods with the same name. Otherwis? library will throws an exception. Also we don't need to set @JavaScriptInterface annotation.

Add interface:

scripto.addInterface("Android", new AndroidInterface(context));

To call showToastMessage method we need to create JS-function with the same name:

function showToastMessage(text) {

Scripto.call('Android', arguments);
 
}
;

In the function we call special library function and pass name of JS-interface and arguments.

Calling the method from JavaScript:

showToastMessage("My super message");

Just as in Java we can use callbacks:

public String showToastMessage(String text) {

Toast.makeText(context, text, Toast.LENGTH_SHORT).show();

return "My super response"; 
}

Calling the method from JavaScript:

showToastMessage("My super message", function(responseString) {

console.log(responseString);
 
}
);

If you want to pass user-defined data type from JavaScript, convert your data to JSON via JSON.stringify(object).

If you need to protect methods from an unauthorized call, then you can protect them @JavaScriptSecure annotation:

ScriptoInterfaceConfig config = new ScriptoInterfaceConfig().enableAnnotationProtection(true);
 scripto.addInterface("Android", new AndroidInterface(this), config);

Do not forget to set an annotation on the method:

@JavaScriptSecure public void showToastMessage(String text) {

  Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
 
}

License

The MIT License

Copyright (c) 2016 Mahach Imangazaliev

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Resources

MaterialDialogBottomSheet is a custom dialog implementation to use BottomSheet MaterialView feature of Lollipop in older versions

Pulls notifications from a remote JSON file and shows them in your app.

Android progress bar with cool animation.

A demo usage of Fresco to show how to load images.

Aeromock is an application server that generates HTML from template files and data files. It enables speedy frontend development without the need for server side modules. Aeromock is referred to as a lightweight mock web application server.

adb-sync is a tool to synchronize files between a PC and an Android device using the ADB (Android Debug Bridge).

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes