自动发帖软件
标题:
苹果脚本里H5 里的 window.at.callFun 示例
[打印本页]
作者:
发帖软件
时间:
昨天 10:11
标题:
苹果脚本里H5 里的 window.at.callFun 示例
苹果脚本里H5 里的 window.at.callFun 示例
//🍎交流 QQ 群:711841924(群一 - 苹果内测群)
//🍎交流 QQ 群:528816639
//🍎 AIWROK iOS 端 window.at.callFun 实现示例
// 阻塞式延迟函数 (Rhino引擎兼容)
function _sleep(ms) {
var start = Date.now();
while (Date.now() - start < ms) {
// 阻塞等待
}
}
/*
* 说明:
* 此文件展示了如何在 AIWROK iOS 环境中实现 window.at.callFun 方法
* 以及如何处理 H5 页面的调用请求
*/
// 初始化 window.at 对象(在WebView上下文中)
function initAtObject(webView) {
printl("初始化 window.at 对象");
if (!webView) {
printl("错误:WebView 对象未提供");
return;
}
// 实现一个全局的原生调用函数
webView._handleH5Call = function(methodName, params) {
printl(`WebView直接调用:${methodName},参数:${JSON.stringify(params)}`);
// 构建模拟的请求URL
const message = {
method: methodName,
params: params,
callbackId: "direct_call"
};
const url = 'aiwrok://callFun?' + JSON.stringify(message);
// 调用handleH5Call处理
const result = handleH5Call(url, webView);
printl(`直接调用返回结果:${result}`);
return result;
};
// 在WebView上下文中初始化window.at对象
const initCode = `
// 创建 at 对象
window.at = window.at || {};
// 实现 callFun 方法
window.at.callFun = function(methodName, ...args) {
console.log('H5调用方法:', methodName, '参数:', args);
try {
// 尝试直接调用原生方法(通过WebView的原生方法)
if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.aiwrok) {
console.log('使用 webkit.messageHandlers 调用');
const message = {
method: methodName,
params: args,
callbackId: Date.now() + Math.random().toString(36).substr(2, 9)
};
window.webkit.messageHandlers.aiwrok.postMessage(message);
return { status: "success", message: "调用已发送" };
} else if (window.android) {
console.log('使用 window.android 调用');
const message = JSON.stringify({
method: methodName,
params: args,
callbackId: Date.now() + Math.random().toString(36).substr(2, 9)
});
return JSON.parse(window.android.callFun(message));
} else {
// 尝试通过prompt调用
console.log('使用 prompt 调用');
const message = {
method: methodName,
params: args,
callbackId: Date.now() + Math.random().toString(36).substr(2, 9)
};
const url = 'aiwrok://callFun?' + JSON.stringify(message);
const result = prompt(url);
console.log('收到返回:', result);
if (result) {
try {
const parsed = JSON.parse(result);
console.log('解析结果:', parsed);
return parsed.data;
} catch (e) {
console.error('解析返回结果失败:', e);
return { error: '解析返回结果失败' };
}
}
// 尝试使用模拟的原生方法
console.log('使用模拟原生方法');
const mockResponse = {
status: "success",
message: "Mock response from native",
data: {
timestamp: new Date().getTime(),
platform: "iOS",
version: "1.0.0",
method: methodName,
params: args
}
};
return mockResponse;
}
} catch (e) {
console.error('调用失败:', e);
return { error: '调用失败: ' + e.message };
}
};
console.log('window.at.callFun 初始化完成');
`;
// 执行初始化代码
try {
if (typeof webView.evaluateJavaScript === 'function') {
printl("使用 evaluateJavaScript 执行初始化代码");
webView.evaluateJavaScript(initCode);
} else if (typeof webView.stringByEvaluatingJavaScriptFromString === 'function') {
printl("使用 stringByEvaluatingJavaScriptFromString 执行初始化代码");
webView.stringByEvaluatingJavaScriptFromString(initCode);
} else if (typeof webView.loadUrl === 'function') {
printl("使用 loadUrl 执行初始化代码");
const url = 'javascript:' + encodeURIComponent(initCode);
webView.loadUrl(url);
} else {
printl("错误:WebView 没有执行JavaScript的方法");
}
printl("window.at.callFun 初始化完成");
} catch (e) {
printl(`初始化失败:${e.message}`);
}
}
// 处理基础测试方法
function handleTestFunction() {
printl("处理 testFunction 调用");
// 模拟异步操作
_sleep(500);
const result = "Hello from iOS!";
printl(`返回结果:${result}`);
return result;
}
// 处理带参数的方法
function handleTestWithParams(params) {
printl(`处理 testWithParams 调用,参数:${JSON.stringify(params)}`);
// 模拟处理参数
const result = `收到参数:${params.join(', ')}`;
printl(`返回结果:${result}`);
return result;
}
// 处理带回调的方法
function handleTestWithCallback() {
printl("处理 testWithCallback 调用");
// 模拟返回复杂数据
const result = {
status: "success",
message: "Callback test successful",
data: {
timestamp: new Date().getTime(),
platform: "iOS",
version: "1.0.0"
}
};
printl(`返回结果:${JSON.stringify(result)}`);
return result;
}
// 处理复杂数据传递
function handleTestComplexData(dataStr) {
printl("处理 testComplexData 调用");
try {
// 解析 JSON 数据
const data = JSON.parse(dataStr);
printl(`解析数据:${JSON.stringify(data)}`);
// 处理数据
const result = {
received: true,
processedData: data,
timestamp: new Date().getTime(),
message: "Complex data processed successfully"
};
printl(`返回结果:${JSON.stringify(result)}`);
return result;
} catch (e) {
printl(`解析数据失败:${e.message}`);
return { error: `解析数据失败:${e.message}` };
}
}
// 处理获取设备信息
function handleGetDeviceInfo() {
printl("处理 getDeviceInfo 调用");
// 模拟设备信息
const deviceInfo = {
model: "iPhone 14 Pro",
os: "iOS",
osVersion: "16.4",
appVersion: "1.0.0",
deviceId: "device_123456",
screen: {
width: 393,
height: 852,
scale: 3
},
network: "Wi-Fi"
};
printl(`返回设备信息:${JSON.stringify(deviceInfo)}`);
return deviceInfo;
}
// 处理显示原生提示
function handleShowToast(message) {
printl(`处理 showToast 调用,消息:${message}`);
// 显示原生 Toast
try {
toast(message);
printl("Toast 显示成功");
return { success: true, message: "Toast shown successfully" };
} catch (e) {
printl(`显示 Toast 失败:${e.message}`);
return { error: `显示 Toast 失败:${e.message}` };
}
}
// 初始化 WebView 并加载 H5 页面
function loadCallFunExample() {
printl("加载 callFun 示例页面");
// 创建 WebView 并直接设置回调
const webView = new WebView({
// WebView初始化配置
onUrlLoading: function(url) {
printl(`拦截到URL:${url}`);
if (url.startsWith('aiwrok://callFun?')) {
const result = handleH5Call(url, webView);
printl(`onUrlLoading 返回结果:${result}`);
return result;
}
return false;
},
// 其他配置
enableJavaScript: true,
enableDomStorage: true
});
// 显示 WebView
printl("显示 WebView");
webView.show();
// 加载示例页面
const htmlPath = project.getCodePath() + "H5.html";
printl(`加载页面:${htmlPath}`);
webView.loadFile(htmlPath);
// 等待页面加载完成后初始化 at 对象
_sleep(2000); // 增加等待时间,确保页面完全加载
printl("初始化 window.at 对象");
initAtObject(webView);
printl("示例页面加载完成");
}
// 处理H5调用
function handleH5Call(url, webView) {
printl(`收到 H5 调用:${url}`);
// 直接返回一个固定的成功结果,不依赖URL解析
try {
// 从URL中提取方法名
let methodName = "unknown";
// 尝试解析URL参数
let jsonPart = url.substring('aiwrok://callFun?'.length);
printl(`原始jsonPart:${jsonPart}`);
try {
// 尝试解码URL
jsonPart = decodeURIComponent(jsonPart);
printl(`解码后的jsonPart:${jsonPart}`);
// 尝试解析JSON
const message = JSON.parse(jsonPart);
if (message.method) {
methodName = message.method;
printl(`从JSON中提取的方法名:${methodName}`);
}
} catch (e) {
printl(`解析URL失败:${e.message}`);
// 如果解析失败,尝试直接从URL中提取方法名
if (url.includes('method%22%3A%22')) {
const start = url.indexOf('method%22%3A%22') + 14;
const end = url.indexOf('%22', start);
if (start > 14 && end > start) {
methodName = url.substring(start, end);
printl(`从URL中提取的方法名:${methodName}`);
}
}
}
printl(`最终方法名:${methodName}`);
// 根据方法名返回不同的结果
let result;
switch (methodName) {
case 'testFunction':
result = "Hello from iOS!";
break;
case 'testWithParams':
result = "收到参数:测试参数";
break;
case 'testWithCallback':
result = {
status: "success",
message: "Callback test successful",
data: {
timestamp: new Date().getTime(),
platform: "iOS",
version: "1.0.0"
}
};
break;
case 'getDeviceInfo':
result = {
model: "iPhone 14 Pro",
os: "iOS",
osVersion: "16.4",
appVersion: "1.0.0",
deviceId: "device_123456",
screen: {
width: 393,
height: 852,
scale: 3
},
network: "Wi-Fi"
};
break;
case 'showToast':
// 显示Toast
if (typeof toast === 'function') {
toast("Hello from H5!");
}
result = { success: true, message: "Toast shown successfully" };
break;
default:
result = { error: `未知方法:${methodName}` };
}
// 构建响应
const response = {
callbackId: "test_callback_id",
data: result
};
const responseStr = JSON.stringify(response);
printl(`返回结果:${responseStr}`);
// 直接返回响应字符串
return responseStr;
} catch (e) {
printl(`处理H5调用失败:${e.message}`);
const errorResponse = JSON.stringify({ error: e.message });
return errorResponse;
}
}
// 测试函数
function testCallFunImplementation() {
printl("=== AIWROK callFun 实现测试 ===");
// 加载示例页面
loadCallFunExample();
printl("测试完成,请在 H5 页面中点击按钮进行测试");
}
// 运行测试
testCallFunImplementation();
/*
* 使用说明:
* 1. 将此脚本在 AIWROK iOS 环境中运行
* 2. 它会创建一个 WebView 并加载 callFun_example.html 页面
* 3. 在 H5 页面中点击各种按钮测试不同的调用方式
* 4. 查看控制台输出以了解调用过程
*
* 注意:
* - 此实现仅用于演示目的
* - 实际应用中需要根据具体需求扩展方法
* - 对于复杂的数据传递,建议使用 JSON 格式
*/
复制代码
// 🍎交流QQ群:711841924(群)
// 🍎交流QQ群:528816639 (苹果内测群)
// 创建 WebView 实例
var web = new WebView();
// 显示 WebView 界面
web.show();
// 加载本地 HTML 文件
var htmlPath = project.getCodePath() + "h5.html";
web.loadFile(htmlPath);
// 打印加载信息
printl("WebView 已创建并加载本地文件:" + htmlPath);
// 导入日志桥接器
Import("LogBridge.js");
// 初始化日志桥接(会阻塞等待 WebView 加载完成)
LogManagerH5.init(web);
// 延迟执行,确保 H5 页面完全加载
_sleep(3000);
// 发送测试日志到 H5 界面
LogManagerH5.success("系统启动成功");
LogManagerH5.info("WebView 已就绪");
// ============================================
// AIWROK 配置管理器H5集成示例
// ============================================
printl("");
printl("====================================");
printl("主脚本.js");
printl("====================================");
// 导入配置管理器H5集成示例
Import("主脚本.js");
复制代码
欢迎光临 自动发帖软件 (http://www.fatiegongju.com/)
Powered by Discuz! X3.2