Implement game-events listener
This document helps you implement event listeners within your native apps.
Last updated
/** Instantiate the interface and set the context */
class gamezopWebAppInterface(private val mContext: Context) {
/** Get Game Events and Show a toast from the web page */
@JavascriptInterface
fun getGameEvents(gameEvent: String) {
Toast.makeText(mContext, gameEvent, Toast.LENGTH_SHORT).show()
}
}val webView: WebView = findViewById(R.id.webview)
webView.addJavascriptInterface(gamezopWebAppInterface(this), "AndroidBridge")WebView(
initialUrl: url,
javascriptMode: JavascriptMode.unrestricted,
javascriptChannels: Set.from([
JavascriptChannel(
name: 'AndroidBridge', onMessageReceived: (JavascriptMessage message) {
// This is where you can use your game events
print(message.message);
}),
]),
onWebViewCreated: (WebViewController w) {
webViewController = w;
},
)override func viewDidLoad() {
super.viewDidLoad()
let config = WKWebViewConfiguration()
config.userContentController = WKUserContentController()
config.userContentController.add(self, name: "gameState")
let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 200, height: 200),
configuration: config)
view.addSubview(webView)
webView.loadHTMLString(content, baseURL: nil)
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print(message.body)
}