Top Related Projects
chrome browser of android version from chromium open project
Beautiful and customizable Android Activity that shows web pages within an app.
Enhanced WebView component for Android that works as intended out of the box
Proof of concept Android WebView implementation based on Chromium code
Quick Overview
Safe-java-js-webview-bridge is a library that provides a secure way to establish communication between JavaScript in a WebView and Java in an Android application. It aims to mitigate security risks associated with traditional WebView JavaScript interfaces by implementing a message-based communication system.
Pros
- Enhances security by avoiding direct method exposure through
addJavascriptInterface
- Supports bidirectional communication between Java and JavaScript
- Easy to integrate into existing Android projects
- Allows for asynchronous communication, improving performance
Cons
- May require refactoring of existing code that uses traditional WebView JavaScript interfaces
- Limited documentation and examples available
- Not actively maintained (last update was several years ago)
- Potential performance overhead due to message-based communication
Code Examples
- Initializing the bridge in Java:
WebView webView = findViewById(R.id.webview);
SafeWebView safeWebView = new SafeWebView(webView);
safeWebView.addJavascriptInterface(new MyJavaScriptInterface(), "Android");
- Sending a message from JavaScript to Java:
window.Android.postMessage(JSON.stringify({
action: 'getData',
params: { id: 123 }
}));
- Handling messages in Java:
public class MyJavaScriptInterface extends JavascriptInterface {
@Override
public void onMessage(String message) {
JSONObject json = new JSONObject(message);
String action = json.getString("action");
if ("getData".equals(action)) {
// Handle getData action
}
}
}
- Sending a message from Java to JavaScript:
safeWebView.loadUrl("javascript:handleMessage(" +
JSONObject.quote(message) + ")");
Getting Started
- Add the library to your project (e.g., via Gradle):
implementation 'com.github.pedant:safe-java-js-webview-bridge:1.0.0'
- Initialize the SafeWebView in your activity:
WebView webView = findViewById(R.id.webview);
SafeWebView safeWebView = new SafeWebView(webView);
safeWebView.addJavascriptInterface(new MyJavaScriptInterface(), "Android");
- Implement the JavascriptInterface in your Java code:
public class MyJavaScriptInterface extends JavascriptInterface {
@Override
public void onMessage(String message) {
// Handle incoming messages from JavaScript
}
}
- Use the
postMessage
method in your JavaScript code to communicate with Java:
window.Android.postMessage(JSON.stringify({
action: 'someAction',
params: { key: 'value' }
}));
Competitor Comparisons
chrome browser of android version from chromium open project
Pros of AndroidChromium
- Full-featured Chromium-based browser implementation for Android
- Extensive documentation and community support
- Regular updates and maintenance
Cons of AndroidChromium
- Larger codebase and more complex implementation
- Higher resource requirements for integration
- Steeper learning curve for developers
Code Comparison
safe-java-js-webview-bridge:
@JavascriptInterface
public String getToken() {
return Token.getToken();
}
AndroidChromium:
public class ChromiumActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeChromium();
}
}
The safe-java-js-webview-bridge focuses on providing a secure interface between Java and JavaScript in WebViews, while AndroidChromium offers a complete Chromium-based browser implementation. The code snippets illustrate the difference in scope and complexity between the two projects.
safe-java-js-webview-bridge is more suitable for developers who need a lightweight solution for secure WebView communication. AndroidChromium is better suited for projects requiring a full-featured browser implementation with advanced capabilities.
Both projects have their merits, and the choice between them depends on the specific requirements of the application being developed. safe-java-js-webview-bridge offers simplicity and focused functionality, while AndroidChromium provides a comprehensive browser solution at the cost of increased complexity.
Beautiful and customizable Android Activity that shows web pages within an app.
Pros of FinestWebView-Android
- Offers a more comprehensive and customizable WebView solution with additional features like progress bars, menus, and themes
- Provides an easy-to-use builder pattern for quick implementation and configuration
- Includes built-in support for various UI elements and animations
Cons of FinestWebView-Android
- Larger library size and potentially higher resource usage due to additional features
- May require more setup and configuration for simple use cases
- Less focused on security aspects compared to safe-java-js-webview-bridge
Code Comparison
FinestWebView-Android:
new FinestWebView.Builder(activity)
.showUrl(false)
.titleDefault("My Web Page")
.showSwipeRefreshLayout(true)
.webViewBuiltInZoomControls(true)
.show("https://example.com");
safe-java-js-webview-bridge:
WebView webView = (WebView) findViewById(R.id.webview);
JsBridge jsBridge = new JsBridge(webView);
jsBridge.register("jsMethod", new BridgeHandler() {
@Override
public void handler(String data, CallBackFunction function) {
// Handle JavaScript call
}
});
The code comparison shows that FinestWebView-Android focuses on easy customization and setup of the WebView, while safe-java-js-webview-bridge emphasizes secure communication between JavaScript and Java. FinestWebView-Android provides a more streamlined API for creating and configuring WebViews, whereas safe-java-js-webview-bridge offers a targeted solution for bridging JavaScript and Java interactions securely.
Enhanced WebView component for Android that works as intended out of the box
Pros of Android-AdvancedWebView
- More comprehensive feature set, including file chooser, custom user agents, and multiple window support
- Better handling of JavaScript interfaces and enhanced security measures
- Active development with regular updates and bug fixes
Cons of Android-AdvancedWebView
- Larger codebase, which may increase app size and complexity
- Steeper learning curve due to additional features and customization options
- May require more setup and configuration compared to the simpler safe-java-js-webview-bridge
Code Comparison
Android-AdvancedWebView:
AdvancedWebView mWebView = findViewById(R.id.webview);
mWebView.setListener(this, this);
mWebView.loadUrl("https://example.com");
safe-java-js-webview-bridge:
WebView webView = findViewById(R.id.webview);
JsBridge jsBridge = new JsBridge(webView);
jsBridge.register("nativeMethod", new JsBridge.Handler() { ... });
The Android-AdvancedWebView provides a more feature-rich implementation with built-in listener support, while safe-java-js-webview-bridge focuses on a simpler bridge between JavaScript and Java. Android-AdvancedWebView offers more out-of-the-box functionality, whereas safe-java-js-webview-bridge requires less setup for basic bridging needs.
Proof of concept Android WebView implementation based on Chromium code
Pros of chromeview
- Uses the Chromium engine, providing better web standards compatibility and performance
- Offers more advanced features like WebRTC and Web Audio API support
- Provides a more consistent browsing experience across different Android versions
Cons of chromeview
- Larger file size and increased app complexity due to bundling Chromium
- Potentially higher memory usage compared to the native WebView
- May require more frequent updates to keep up with Chromium releases
Code Comparison
safe-java-js-webview-bridge:
@JavascriptInterface
public String getData() {
return "Safe data from Java";
}
chromeview:
mWebView.addJavascriptInterface(new Object() {
@JavascriptInterface
public String getData() {
return "Data from Chromium-based WebView";
}
}, "Android");
Both projects aim to provide a bridge between Java and JavaScript in Android WebViews, but they differ in their approach and underlying technology. safe-java-js-webview-bridge focuses on security and simplicity, while chromeview offers a more feature-rich and modern web rendering engine at the cost of increased complexity and resource usage.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Safe Java-JS WebView Bridge
æå¼ä½¿ç¨é«é£é©çWebView addJavascriptInterfaceæ¹æ³ï¼éè¿å¯¹jså±è°ç¨å½æ°ååè°å½æ°çå è£ ï¼æ¯æå¼æ¥åè°ï¼æ¹æ³åæ°æ¯æjsææå·²ç¥çç±»åï¼å æ¬numberãstringãbooleanãobjectãfunctionã
å®è£
使ç¨Safe Java-JS WebView Bridgeæç®åçåæ³å°±æ¯åä¸é¢è¿æ ·æ·»å 项ç®ä¾èµã
Maven
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>cn.pedant.safewebviewbridge</groupId>
<artifactId>library</artifactId>
<version>1.4</version>
<type>aar</type>
</dependency>
Gradle
repositories {
mavenCentral()
}
dependencies {
compile 'cn.pedant.safewebviewbridge:library:1.4'
}
Sample
ç¨æ³
å¦ä½å¼å§
åå§åWebview WebSettingsæ¶å 许jsèæ¬æ§è¡ï¼åæ¶ä½¿ç¨ä½ çæ³¨å ¥ååæ³¨å ¥ç±»æ¥å®ä¾åä¸ä¸ªInjectedChromeClient对象ï¼ç¶åå ³èå°ä½ çWebviewå®ä¾ãå¦demoä¸çä¾åï¼é¡µé¢ä¸å¼ç¨ç对象å为HostAppï¼æå®çæ³¨å ¥ç±»ä¸ºHostJsScopeï¼ï¼
WebView wv = new WebView(this);
WebSettings ws = wv.getSettings();
ws.setJavaScriptEnabled(true);
wv.setWebChromeClient(
new InjectedChromeClient("HostApp", HostJsScope.class)
);
wv.loadUrl("file:///android_asset/test.html");
èªå®ä¹WebChromeClientåç±»
å¦æä½ éè¦å®ç°èªå·±çWebChromeClientåç±»ï¼ç¶å设置å°WebViewã为äºä¿æInjectedChromeClientçåè½ï¼ä½ éè¦å°æ¤ç±»ç»§æ¿èªInjectedChromeClientï¼åæ¶åä¸é¢è¿æ ·è¦çè¿ä¸ä¸ªæ¹æ³ã
public class CustomChromeClient extends InjectedChromeClient {
public CustomChromeClient (String injectedName, Class injectedCls) {
super(injectedName, injectedCls);
}
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
// to do your work
// ...
return super.onJsAlert(view, url, message, result);
}
@Override
public void onProgressChanged (WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
// to do your work
// ...
}
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
// to do your work
// ...
return super.onJsPrompt(view, url, message, defaultValue, result);
}
}
æ¹æ³çå®ä¹
éè¦æ³¨å ¥å°ç½é¡µçæ¹æ³ï¼å¿ é¡»å¨æ³¨å ¥ç±»ä¸å®ä¹ä¸ºpublic staticä¸ç¬¬ä¸ä¸ªåæ°æ¥æ¶WebViewï¼å ¶ä»åæ°çç±»åå¯ä»¥æ¯intãlongãdoubleãbooleanãStringãJSONObjectãJsCallbackãæ¹æ³æ§è¡æ¶ä¼é»è®¤å°å½åWebviewçå®ä¾æ¾å°ç¬¬ä¸ä¸ªåæ°ï¼æä»¥ä½ çå®ä¹å¯è½çèµ·æ¥åè¿æ ·åçï¼
public static void testA (WebView webView) {}
ç½é¡µè°ç¨å¦ä¸ï¼
HostApp.testA();
æ¹æ³çéè½½
å¨å®ä¹æ¶ï¼æ¯æä¸ååæ°ç±»åæåæ°ä¸ªæ°çæ¹æ³éè½½ï¼å¦ï¼
public static int overloadMethod(WebView view, int val) {
return val;
}
public static String overloadMethod(WebView view, String val) {
return val;
}
ä½éè¦æ³¨æçæ¯ï¼ç±äºJSä¸æ°åç±»åä¸åºåæ´åãé¿æ´åãæµ®ç¹ç±»åçï¼æ¯ç»ä¸ç±64ä½æµ®ç¹æ°è¡¨ç¤ºï¼æ Javaæ¹æ³å¨å®ä¹æ¶int/long/double被å½ä½æ¯ä¸ç§ç±»åï¼ä¹å³ï¼
public static int overloadMethod(WebView view, int val) {
return val;
}
public static long overloadMethod(WebView view, long val) {
return val;
}
public static double overloadMethod(WebView view, double val) {
return val;
}
ä¸é¢è¿ä¸ä¸ªæ¹æ³å¹¶æ²¡æåçéè½½ï¼HostApp.overloadMethod(1)è°ç¨æ¶åªä¼è°ç¨æåä¸ä¸ªå®ä¹çæ¹æ³ï¼doubleç±»åå®ä¹çé£ä¸ªï¼ã
æ¹æ³çè¿åå¼
Javaå±æ¹æ³å¯ä»¥è¿åvoid æ è½è½¬ä¸ºå符串çç±»åï¼å¦intãlongãStringãdoubleãfloatçï¼æ å¯åºååçèªå®ä¹ç±»åãå ³äºèªå®ä¹ç±»åçè¿åå¯ä»¥åè§Demoä¸âä»Javaå±è¿åJava对象â项对HostApp.retJavaObject()çè°ç¨ãå¦å¤å¦ææ¹æ³å®ä¹æ¶è¿åvoidï¼é£ä¹ç½é¡µç«¯è°ç¨å¾å°çè¿åå¼ä¸ºnullã
å¦ææ¹æ³æ§è¡è¿ç¨ä¸åºç°å¼å¸¸ï¼é£ä¹å¨ç½é¡µJS端ä¼æåºå¼å¸¸ï¼å¯ä»¥catchåæå°è¯¦ç»çé误说æã
å ³äºå¼æ¥åè°
举ä¾è¯´æï¼é¦å ä½ å¯ä»¥å¨Javaå±å®ä¹å¦ä¸æ¹æ³ï¼è¯¥æ¹æ³çä½ç¨æ¯å»¶è¿è®¾å®çæ¶é´ä¹åï¼ç¨ä½ ä¼ å ¥çåæ°åè°Jså½æ°ï¼
public static void delayJsCallBack(WebView view, int ms, final String backMsg, final JsCallback jsCallback) {
TaskExecutor.scheduleTaskOnUiThread(ms*1000, new Runnable() {
@Override
public void run() {
jsCallback.apply(backMsg);
}
});
}
é£ä¹å¨ç½é¡µç«¯çè°ç¨å¦ä¸ï¼
HostApp.delayJsCallBack(3, 'call back haha', function (msg) {
HostApp.alert(msg);
});
å³3ç§ä¹åä¼å¼¹åºä½ ä¼ å ¥ç'call back haha'ä¿¡æ¯ã æ ä»ä¸é¢çä¾åæ们å¯ä»¥çåºï¼ä½ å¨ç½é¡µç«¯å®ä¹çåè°å½æ°æ¯å¯ä»¥éå å¤ä¸ªåæ°ï¼Javaæ¹æ³å¨æ§è¡åè°æ¶éè¦å¸¦å ¥ç¸åºçå®åå°±è¡äºãå½ç¶è¿éçåè°å½æ°çåæ°ç±»åç®åè¿ä¸æ¯æè¿å¤æçç±»åï¼ä» æ¯æè½å¤è¢«è½¬ä¸ºå符串çç±»åã
å¦å¤éè¦æ³¨æçæ¯ä¸è¬ä¼ å ¥å°Javaæ¹æ³çjs functionæ¯ä¸æ¬¡æ§ä½¿ç¨çï¼å³å¨Javaå±jsCallback.apply(...)ä¹åä¸è½ååèµ·åè°äºãå¦æéè¦ä¼ å ¥çfunctionè½å¤å¨å½å页é¢çå½å¨æå å¤æ¬¡ä½¿ç¨ï¼è¯·å¨ç¬¬ä¸æ¬¡applyå**setPermanent(true)**ãä¾å¦ï¼
public static void setOnScrollBottomListener (WebView view, JsCallback jsCallback) {
jsCallback.setPermanent(true);
...
}
å°å¿è¿å¤§æ°å
JSä¸ä½¿ç¨è¿å¤§æ°åæ¶ï¼å¯è½ä¼å¯¼è´ç²¾åº¦ä¸¢å¤±æè é误çæ°åç»æï¼å¦ä¸é¢ï¼
HostApp.passLongType(14102300951321235)
ä¼ å ¥ä¸ä¸ªå¤§æ°14102300951321235å°Javaå±ï¼ä½Javaå±æ¥æ¶çæ°åå®é ä¸å°ä¼æ¯14102300951321236è¿æ ·ä¸ä¸ªé误çæ°åï¼æ以å½éè¦ä½¿ç¨å¤§æ°çæ æ¯ä¸æ¶ï¼Javaæ¹æ³åæ°ç±»åæ好å®ä¹ä¸ºStringç±»åï¼èjså±è°ç¨æ¶ä¹è½¬ä¸ºstringï¼æ¯å¦ä¸é¢å°±ä¸º
HostApp.passLongType(14102300951321235+'')ã
æ´å¤å®ç°ç»èè§: http://www.pedant.cn/2014/07/04/webview-js-java-interface-research/
åå¸æ¶é²æ··æ·
åå¸æ¶éå¨ä½ çæ··æ·é ç½®å å ¥åä¸é¢è¿æ ·ç代ç ï¼æ³¨æè¿åå°é¡µé¢çèªå®ä¹Java类以åæ³¨å ¥ç±»é½è¦æ¢æä½ é¡¹ç®ä¸å®é 使ç¨ç±»å:
#--------------- BEGIN: Gsoné²æ··æ· ----------
-keepattributes *Annotation*
-keep class sun.misc.Unsafe { *; }
-keep class com.idea.fifaalarmclock.entity.***
-keep class com.google.gson.stream.** { *; }
#--------------- END ----------
#--------------- BEGIN: è¿åå°é¡µé¢çèªå®ä¹Java对象é²æ··æ· ----------
-keepclassmembers class cn.pedant.SafeWebViewBridge.sample.HostJsScope$RetJavaObj{ *; }
#--------------- END ----------
#--------------- BEGIN: 注å
¥å°é¡µé¢çæ¥å£ç±»é²æ··æ· ----------
-keepclassmembers class cn.pedant.SafeWebViewBridge.sample.HostJsScope{ *; }
#--------------- END ----------
License
The MIT License (MIT)
Copyright (c) 2014 Pedant(http://pedant.cn)
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.
Top Related Projects
chrome browser of android version from chromium open project
Beautiful and customizable Android Activity that shows web pages within an app.
Enhanced WebView component for Android that works as intended out of the box
Proof of concept Android WebView implementation based on Chromium code
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot