Kamome
Kamome是一个用于iOS和Android应用程序的WebView库。这个库通过Swift、Java或Kotlin编写的本地代码在WebView中的JavaScript和本地代码之间架起了一座桥梁。
Kamome为iOS和Android提供通用的JavaScript接口。
如果您使用WebView构建Flutter应用程序,请查看kamome_flutter插件。
快速使用
从JS代码发送消息到本地代码
-
从JavaScript代码发送消息
// JavaScript import { KM } from "kamome" // Uses async/await. try { // Sends `echo` command. const result = await KM.send('echo', { message: 'Hello' }); // Receives a result from the native code if succeeded. console.log(result.message); } catch(error) { // Receives an error from the native code if failed. console.log(error); }
-
iOS上接收消息
// Swift private lazy var webView: WKWebView = { let webView = WKWebView(frame: self.view.frame) return webView }() private var client: Client! override func viewDidLoad() { super.viewDidLoad() // Creates the Client object with the webView. client = Client(webView) // Registers `echo` command. client.add(Command("echo") { commandName, data, completion in // Received `echo` command. // Then sends resolved result to the JavaScript callback function. completion.resolve(["message": data!["message"]!]) // Or, sends rejected result if failed. //completion.reject("Echo Error!") }) let htmlURL = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "www")! webView.loadFileURL(htmlURL, allowingReadAccessTo: htmlURL) view.addSubview(webView) }
【注意】 此框架仅支持WKWebView。不支持UIWebView。
-
Android上接收消息
// Kotlin private var client: Client? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val webView = findViewById<WebView>(R.id.webView) // Creates the Client object with the webView. client = Client(webView) // Registers `echo` command. client.add(Command("echo") { commandName, data, completion -> // Received `echo` command. // Then sends resolved result to the JavaScript callback function. val map = HashMap<String?, Any?>() map["message"] = data!!.optString("message") completion.resolve(map) // Or, sends rejected result if failed. //completion.reject("Echo Error!") }) webView.loadUrl("file:///android_asset/www/index.html") }
从本地代码发送消息到JS代码
-
iOS上从本地代码发送消息
// Swift // Send a data to the JS code. client.send(["greeting": "Hello! by Swift"], commandName: "greeting") { (commandName, result, error) in // Received a result from the JS code. guard let result = result else { return } print("result: \(result)") }
-
Android上从本地代码发送消息
// Kotlin // Sends a data to the JS code. val data = HashMap<String?, Any?>() data["greeting"] = "Hello! by Kotlin" client?.send(data, "greeting") { commandName, result, error -> // Received a result from the JS code. Log.d(TAG, "result: $result") }
-
JavaScript代码上接收消息
// JavaScript // Adds a receiver that receives a message sent by the native client. KM.addReceiver('greeting', (data, resolve, reject) => { // The data is the object sent by the native client. console.log(data.greeting); // Runs asynchronous something to do... setTimeout(() => { // Returns a result as any object or null to the native client. resolve('OK!'); // If the task is failed, call `reject()` function. //reject('Error message'); }, 1000); });
在您的项目中包含库
1. JavaScript
npm
-
npm install
npm install kamome
-
在JavaScript中写入以下导入语句
import { KM } from "kamome"
手动安装
-
下载最新的 Kamome SDK
-
导入 kamome.js 或 kamome.min.js
<script src="/path/to/kamome[.min].js"></script>
或者,您可以将 kamome.js 文件中的所有代码(位于 kamome.js)复制到您的 JavaScript 中。
-
(可选) TypeScript
如果您手动安装 kamome.js 并使用 TypeScript,您下载 kamome.d.ts 文件,并在项目目录(如
@types
)中导入该文件。
2. iOS App
CocoaPods
Kamome 可通过 CocoaPods 获得。要安装它,只需将以下行添加到您的 Podfile 中即可
pod "kamome"
Carthage
Kamome 可通过 Carthage 获得。要安装,只需在 Cartfile 中添加以下行:
github "HituziANDO/kamome"
在终端运行以下命令。
carthage update --use-xcframeworks
Swift 包管理器
Kamome 可通过 Swift 包管理器获得。要使用 Xcode 安装,请指定 Kamome 的 git URL。
https://github.com/HituziANDO/kamome.git
手动安装
- 将 kamome.xcframework 拖放到 Xcode 项目中
- 在目标中点击“通用”标签
- 在“框架、库和捆绑内容”中,为 kamome.xcframework 选择“捆绑并签名”
导入框架
在源代码中写导入声明
import kamome
3. 安卓应用
Gradle
在 build.gradle(项目级别)中添加以下代码。
allprojects {
repositories {
maven {
url 'https://hituziando.github.io/kamome/android/repo'
}
}
}
在 build.gradle(应用级别)中添加以下代码。
dependencies {
implementation 'jp.hituzi:kamome:5.2.0'
}
手动安装
- 将 kamome-x.x.x.jar 复制到 YOUR_ANDROID_STUDIO_PROJECT/app/libs 目录
- 在 AndroidStudio 中同步项目
配置
Timeout to request from the JS code to the native code
KM.send
方法在 JavaScript 中期望有一个在指定时间内返回的 resolve
或 reject
响应。如果请求超时,回调将使用 requestTimeout
错误调用 reject
。您可以更改默认请求超时。请参见以下内容。
// JavaScript
// Set default timeout in millisecond.
KM.setDefaultRequestTimeout(15000);
如果指定的时间小于或等于 0,则请求超时功能将禁用。
如果您想单独指定请求超时,请在 KM.send
方法的第 3 个参数中设置以毫秒为单位的超时时间。
// JavaScript
// Set a timeout in millisecond at 3rd argument.
const promise = KM.send(commandName, data, 5000);
Optional: console.log for WKWebView on iOS/macOS
ConsoleLogAdapter
类可以通过 console.log
、console.warn
、console.error
和 console.assert
在 JavaScript 中输出日志到 Xcode 控制台。
// Swift
ConsoleLogAdapter().setTo(webView)
Use Custom Logger
ConsoleLogAdapter 默认使用 print
方法输出日志。如果您使用自己的日志记录器,则需要实现 ConsoleLoggable
协议。请参见以下代码。
// Swift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let consoleLogAdapter = ConsoleLogAdapter()
// Set the custom logger.
consoleLogAdapter.logger = self
consoleLogAdapter.setTo(webView)
}
}
// Implement ConsoleLoggable protocol.
extension ViewController: ConsoleLoggable {
public func consoleLog(_ logMessage: Any) {
// TODO: Output a `logMessage` with the custom logger.
}
}
独立浏览器
如果没有Kamome的iOS/Android本地客户端,也就是说,使用独立浏览器运行时,您可以注册每个命令的处理过程。
// JavaScript
KM.browser
.addCommand("echo", function (data, resolve, reject) {
// Received `echo` command.
// Then sends resolved result to the JavaScript callback function.
resolve({ message: data["message"] });
// Or, sends rejected result if failed.
//reject("Echo Error!");
});
更多信息,请参阅我的iOS示例项目和Android示例项目。