SwiftWKBridge
在 Swift 和 WKWebView 之间发送消息的优雅方式。
您不需要编写任何 JavaScript 代码。
同时,网页开发者也不需要编写额外的 JavaScript 代码。
示例
使用原生代码定义 JavaScript 函数非常简单
let plg: (String) -> Void = {
print("🌏 [WebView]:", $0)
}
// the first arg is the function name
webView.injector.inject(path: "window.bridge.log", plugin: plg)
// the web developer can invoke this function directly
// window.bridge.log("hello world");
使用回调定义函数
let plg: (String, Callback) -> Void = {
$1("Got it. ", $0)
}
// Subscripts is supported
webView.injector["window.bridge.test"] = plg
// js: window.bridge.test("message", console.log)
编码
struct User: Codable {
var name: String
var age: Int
var nickname: String?
}
let plg: (User, Callback) -> Void = { user, callback in
var user = user
user.nickname = "Nickname"
user.age = 10
callback(user)
}
webView.injector["window.bridge.test"] = plg
// window.bridge.test({ name: "Octree", age: 100 }, (user) => { /* ... */ })
CSS 注入器
除此之外,您还可以将 CSS 注入到您的 WebView 中
webView.injector.cssInjector.inject(css: source, forKey: key)
// remove css
webView.injector.cssInjector.removeCSS(forKey: key)
夜间模式
webView.nightFall()
webView.sunrise()
安装
CocoaPods
pod 'SwiftWKBridge'
Swift包管理器
- 文件 > Swift包 > 添加包依赖
- 添加 https://github.com/octree/SwiftWKBridge.git
- 选择“升级至下一个主要版本”,“1.0.0”
作者
Octree, [email protected]
许可
SwiftWKBridge在MIT许可下提供。更多信息请查看LICENSE文件。