【无标题】cocos与外部laya或者web交互

一.电脑:

电脑网页:cocos --->laya

this.webview._impl._iframe.contentWindow.postMessage("cocosToLaya", "*");//laya

//这里是浏览器环境下, 接收web传过来的消息//cocos

window.addEventListener("message", function(event){

console.log( '这里是接收到的消息,消息内容在event.data属性中1111', event )

console.log(event.data);

}, false)

电脑网页:laya --->cocos

if (window.isNative) {//laya

//android or ios

document.location = 'testkey://a=1&b=2'

} else {

//browser 浏览器下,向cocos发送消息

parent.postMessage("------------hello!-----cocos---------", "*")

}

if (cc.sys.isBrowser) {//cocos

//这里是浏览器环境下, 接收web传过来的消息

window.addEventListener('message', function (e) {

console.log("----cocos---", e.data);

test();

})

}

二.手机

手机安卓:cocos --->laya

this.webview.evaluateJS('window.test()');//cocos

let data = {id:123456}

data = JSON.stringify(data); //注意这里需要把参数序列化

this.webView.evaluateJS("setBackgroundColor(" + data + ")");

function test() { //laya

console.log("-------laya--------data-------" + data)

}

window.test = test;

手机安卓:laya --->cocos

if (window.isNative) { //laya

//android or ios

document.location = 'testkey://a=1&b=2'

} else {

//browser 浏览器下,向cocos发送消息

parent.postMessage("------------hello!-----cocos---------", "*")

}

window.addEventListener("message", function(event){ //laya,注意:这个会收到上面的 parent.postMessage("------------hello!-----cocos---------", "*")消息

console.log( '这里是接收到的消息,消息内容在event.data属性中1111', event )

console.log(event.data);

}, false)

//laya

document.location = 'testkey://a=1&b=2';

传递参数

var id=111;

var name="ganme"

document.location = 'testkey://webview?id='+id+'&name='+name;

//cocos

onLoad() {

// 这里是与内部页面约定的关键字,请不要使用大写字符,会导致 location 无法正确识别。

let scheme = "testkey";

function jsCallback (target, url) {

// 这里的返回值是内部页面的 URL 数值,需要自行解析自己需要的数据。

let str = url.replace(scheme + '://', ''); // str === 'a=1&b=2'

console.log("------1testkeytestkey-1----target:"+JSON.stringify(target));//{"__nativeRefs":{},"src":"http://tan-xin-game.mytingyou.com/client/Disucz/test/bin/index.html?sdk=3\&ip=47.92.24.73:12347\&debug=true"}

console.log("------1testkeytestkey-2----str:"+str);//a=1&b=2

console.log("------1testkeytestkey-3----url:"+url);//testkey://a=1&b=2

}

this.webview.setJavascriptInterfaceScheme(scheme);

this.webview.setOnJSCallback(jsCallback);

commonUtils.initALLRES();

},

相关推荐
Icoolkj3 小时前
VuePress 与 VitePress 深度对比:特性、差异与选型指南
前端·javascript·vue.js
^Rocky4 小时前
JavaScript性能优化实战
开发语言·javascript·性能优化
西陵4 小时前
Nx带来极致的前端开发体验——任务编排
前端·javascript·架构
笑鸿的学习笔记4 小时前
JavaScript笔记之JS 和 HTML5 的关系
javascript·笔记·html5
萌萌哒草头将军6 小时前
10个 ES2025 新特性速览!🚀🚀🚀
前端·javascript·vue.js
gnip6 小时前
http缓存
前端·javascript
JohnYan7 小时前
工作笔记 - 微信消息发送和处理
javascript·后端·微信
陈陈爱java8 小时前
Spring八股文
开发语言·javascript·数据库
@大迁世界8 小时前
用 popover=“hint“ 打造友好的 HTML 提示:一招让界面更“懂人”
开发语言·前端·javascript·css·html
烛阴8 小时前
【TS 设计模式完全指南】用工厂方法模式打造你的“对象生产线”
javascript·设计模式·typescript