设置消息回调(:setMessageCallback)
函数
webView:setMessageCallback(回调函数)
参数
- 回调函数: function(message) 形式的函数,其中 message 为网页端发送过来的消息内容(字符串类型)。
说明
设置网页向脚本发送消息时的回调函数。当网页端通过相应的注入方法向脚本发送消息时(如 window.webkit.messageHandlers...),该回调函数会被触发。
示例
1. HTML 前端代码 (test.html)
在网页中,需要通过 window.webkit.messageHandlers.tsBridge.postMessage(数据) 向脚本发送消息:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>TAS WebView 交互测试</title>
</head>
<body>
<button onclick="sendMessage()">点我发送消息给 Lua</button>
<script>
function sendMessage() {
// 向脚本发送字符串消息
window.webkit.messageHandlers.tsBridge.postMessage("你好,我是来自网页的消息!");
}
</script>
</body>
</html>
2. Lua 脚本代码
在脚本中加载网页,并设置接收消息的回调:
local view =
webView.init {
x = 0, --屏幕横坐标 int 整数 必填
y = 0, -- 屏幕纵坐标 int 整数 必填
width = 1125, -- 宽度 int 整数 必填
height = 2436, --高度 int 整数 必填
html = [[<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>TAS WebView 交互测试</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
button {
padding: 15px 30px;
font-size: 18px;
color: white;
background-color: #007AFF; /* iOS 默认的蓝色 */
border: none;
border-radius: 10px; /* 圆角 */
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
button:active {
background-color: #0056b3;
}
</style>
</head>
<body>
<button onclick="sendMessage()">点我发送消息给 TAS</button>
<script>
function sendMessage() {
// 向 TAS 脚本发送字符串消息
window.webkit.messageHandlers.tsBridge.postMessage("你好,我是来自网页的消息!");
}
</script>
</body>
</html>]], -- html 可选 和url 字段 必须存在一项 文本
alpha = 100, -- 透明度 可选 默认 0 -100 整数 默认100
-- rotate = 90, --向右旋转90度 可选 -90 为左旋转。 默认 0
radius = 5.0, -- 圆角 可选
hit = true, --是否可拖动 可选 默认 true
userInteractionEnabled = true -- 是否可交互 为false 时 拖动失效 可选 默认 true
}
view:show()
view:setMessageCallback(
function(message) --接收来自webView 的消息
print("收到网页消息: " .. message)
end
)
sys.msleep(10000) --延迟10秒 在停止脚本