Api Deep Interaction
Overview
This document primarily covers the usage methods and action lists for deep client interactions. For the access source code, refer to https://github.com/JorMi-03/DJBridge
Action List
2J Sends Actions to the Platform
action | data | Description | ||
---|---|---|---|---|
Actions Automatically Executed by 2J | ||||
htmlPageShow | / | The HTML page has been displayed. To fix the startup white screen issue, you can perform the display operation after receiving this action. | ||
loadFrameworkStart | / | The framework starts loading (the engine and the main framework code have been loaded at this point). | ||
loadFrameworkEnd | / | The framework has finished loading (the initial framework and the common resources included in the framework have been loaded at this point). | ||
showGameRoomView | / | The game room view has been displayed. | ||
showGameView | / | The game view has been displayed. | ||
firstAssetsLoadEnd | / | The first assets have finished loading (the room list / the game interface have been displayed at this point). | ||
notSufficientAmount | { // The amount needed for insufficient balance amout: number gameId: number rechargeFrom: number } | // Insufficient balance (if using applyActions to register, the default behavior of 2J will be ignored) rechargeFrom: 8: Insufficient balance 10: Insufficient balance for subgame settlement 11: Insufficient balance for subgame betting 12: Insufficient balance for subgame room entry | ||
Actions that can be used after applying applyActions | ||||
closeGame | / | Close the game window (platform needs to close 2J's game window "iframe/webview" here) |
Platform To 2J Action
action | send data | callback data | Description | |
---|---|---|---|---|
The following actions can be executed after receiving loadFrameworkStart | ||||
applyActions | Array<string> | / | Apply actions that can be executed by 2J to Bridge, actions that 2J have default behaviors need to be applied, and 2J will ignore the default behavior and use the platform-provided actions | |
setMusicOpen | boolean | / | Set the music switch (controls the background music) | |
setEffectOpen | boolean | / | Set the sound switch (controls the sound effects) | |
isMusicOpen | / | boolean | Whether the music is enabled | |
isEffectOpen | / | boolean | Whether the sound effects are enabled | |
The following actions must be executed after receiving loadFrameworkEnd | ||||
openDebug | / | / | // Enable API game debug function | |
The following actions must be executed after receiving (firstAssetsLoadEnd) first resource loading completion push | ||||
getScreenshotBase64 | / | string | Get screenshot base64 data, the platform can use this data to simulate displaying platform pop-ups in the 2J game interface (note: the case where the first game screen is not displayed) | |
gamePause | / | / | Pause the game main loop (in some platform interface performance optimization cases, pause the game) | |
gameResume | / | / | Resume the game main loop | |
getGameViewType | / | / | Get the current game interface type 0: Unknown 1: Room list 2: Game interface | |
getAllRoomInfo | / | { gameId: number items: { id: number; betList: number[] } } | Get all room list configuration data (Note: Only slots and 100-person online game have betList) Betting levels (slots as an example), each game will have betting bet levels | |
updateUserBalance | / | / | Manually refresh user balance | |
The following actions must be executed after receiving (firstAssetsLoadEnd) first resource loading completion push | ||||
getRoomInfo | / | { gameId: number betList: number[] } | Get the current room configuration data |
Platform To 2J Action Example
Platform To 2J Action
iframe
js
const message = {
action: action,
data: data,
callbackId: callbackId,
};
this.iframe.contentWindow.postMessage(message, this.iframe.src);
Android
java
JSONObject param = new JSONObject();
param.put("action","setMusicOpen");
param.put("data",true);
String jsonString = param.toString();
String jsCode = "javascript:DJAndroidBridgeToJs('" + jsonString.replace("'", "\\'") + "')";
iOS
swift
var messageDict: [String: Any] = [
"action": action,
]
if (data != nil) {
messageDict["data"] = data
}
if (callbackId != nil) {
messageDict["callbackId"] = callbackId
}
do {
let jsonData = try JSONSerialization.data(withJSONObject: messageDict, options: [])
if let jsonString = String(data: jsonData, encoding: .utf8) {
let escapedJsonString = jsonString.replacingOccurrences(of: "'", with: "\\'")
evaluateJavaScript(
"window.DJGameToPlatformJs('\(escapedJsonString)')",
completionHandler: { (result, error) in
if let error = error {
print("send message to js error: \(error.localizedDescription)")
}
})
}
} catch {
print("JSON decode error: \(error.localizedDescription)")
}
2J The executed code
The situation where there is no return value
js
window.DJGameToPlatformJs({
action: "setMusicOpen",
data: true,
});
There are cases where there is a return value
- send
js
window.DJGameToPlatformJs({
action: "isMusicOpen",
data: null,
// The id here needs to be handled by the user, and each request needs to be different to avoid conflicts
callbackId: 1,
});
// The platform will send the callback action according to the callbackId
- recv
js
const param = {
action: "callBackAction",
data: {
callbackId: 1,
data: true,
inputAction: "isMusicOpen",
success: true,
},
};
if (android) {
window["DJAndroidBridge"].onMessageReceived(param);
} else if (iOS) {
window.webkit.messageHandlers.DJiOSBridge.postMessage(param);
} else if (iframe) {
window.parent.postMessage(param, "*");
}
2J To Platform Action
2J Run Code
js
const param = {
action: "xxx",
data: {},
};
if (android) {
window["DJAndroidBridge"].onMessageReceived(param);
} else if (iOS) {
window.webkit.messageHandlers.DJiOSBridge.postMessage(param);
} else if (iframe) {
window.parent.postMessage.postMessage(param, "*");
}
iframe
js
window.addEventListener("message", (event) => {
if (!this.iframe) {
return;
}
if (
event.origin === new URL(this.iframe.src).origin &&
event.source === this.iframe.contentWindow
) {
const data = event.data;
if (typeof data == "object" && data != null && typeof data.action == "string") {
console.log("%c [Iframe on message]: %o", "color: #90ee90", data);
if (data.action == "callBackAction") {
const taskData = data.data || {};
const callbackId = taskData.callbackId;
const callbackData = taskData.data;
const isSuccess = taskData.success;
// The platform will send the callback action according to the callbackId
} else {
// The platform will send the other action
}
}
}
});
iOS (Swift)
swift
init(frame: CGRect) {
let userContentController = WKUserContentController()
self.messageHandler = WebViewMessageHandler(delegate: nil)
userContentController.add(self.messageHandler, name: "DJiOSBridge")
config.userContentController = userContentController
self.uiDelegate = self
}
func userContentController(
_ userContentController: WKUserContentController, didReceive message: WKScriptMessage
) {
if message.name == "DJiOSBridge" {
if let body = message.body as? String {
guard let bodyData = body.data(using: .utf8) else { return }
do {
if let jsonDict = try JSONSerialization.jsonObject(with: bodyData, options: []) as? [String: Any] {
let action = jsonDict["action"] as! String
let data = jsonDict["data"]
if action == "callBackAction" {
let recvData = data as! [String: Any]
let callbackId:Int = recvData["callbackId"] as! Int;
let success = recvData["success"] as! Bool
let retData = recvData["data"]
if (success) {
// success
} else {
// error
}
} else {
// onMessageReceived?(action, data)
}
}
} catch {
print("JSON decode error: \(error.localizedDescription)")
}
}
}
}
Android(Java)
java
DJWebViewJsBridge bridge = new DJWebViewJsBridge(messageReceived);
webview.addJavascriptInterface(bridge,"DJAndroidBridge");
@JavascriptInterface
public void onMessageReceived(String jsonStr) {
try {
JSONObject jsonObject = new JSONObject(jsonStr);
String action = (String) jsonObject.get("action");
if (action.equals("callBackAction")) {
JSONObject recvData = jsonObject.getJSONObject("data");
int callbackId = (int) recvData.get("callbackId");
boolean success = (boolean) recvData.get("success");
Object retData = null;
if (!recvData.isNull("data")) {
retData = recvData.get("data");
}
if (success) {
// success
} else {
// error
}
} else {
// other
}
} catch (JSONException e) {
e.printStackTrace();
}
}