在JavaScript(JS)中调用Native方法通常涉及到一些特定的技术和框架,比如:
以下是一个简单的JSBridge示例,展示了如何在JavaScript中调用Native方法:
// Native层
public class JSBridge {
@JavascriptInterface
public void showToast(String message) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
// 在WebView中添加JS接口
webView.addJavascriptInterface(new JSBridge(), "Android");
// JS层
function callNativeMethod() {
if (window.Android && typeof window.Android.showToast === 'function') {
window.Android.showToast('Hello from JavaScript!');
} else {
console.log('Native bridge not available.');
}
}
// Native层
import WebKit
class ViewController: UIViewController, WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "nativeBridge", let messageBody = message.body as? String {
showToast(messageBody)
}
}
func showToast(_ message: String) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default))
present(alert, animated: true)
}
}
// 配置WKWebView
let contentController = WKUserContentController()
contentController.add(self, name: "nativeBridge")
let config = WKWebViewConfiguration()
config.userContentController = contentController
let webView = WKWebView(frame: .zero, configuration: config)
// JS层
function callNativeMethod() {
if (window.webkit && window.webkit.messageHandlers.nativeBridge) {
window.webkit.messageHandlers.nativeBridge.postMessage('Hello from JavaScript!');
} else {
console.log('Native bridge not available.');
}
}
通过以上方法,可以实现JavaScript与Native代码之间的有效通信,从而扩展Web应用的功能和性能。
领取专属 10元无门槛券
手把手带您无忧上云