【无标题】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();

},

相关推荐
惜.己34 分钟前
javaScript基础(8个案例+代码+效果图)
开发语言·前端·javascript·vscode·css3·html5
长天一色1 小时前
【ECMAScript 从入门到进阶教程】第三部分:高级主题(高级函数与范式,元编程,正则表达式,性能优化)
服务器·开发语言·前端·javascript·性能优化·ecmascript
NiNg_1_2342 小时前
Vue3 Pinia持久化存储
开发语言·javascript·ecmascript
读心悦2 小时前
如何在 Axios 中封装事件中心EventEmitter
javascript·http
神之王楠2 小时前
如何通过js加载css和html
javascript·css·html
余生H2 小时前
前端的全栈混合之路Meteor篇:关于前后端分离及与各框架的对比
前端·javascript·node.js·全栈
流烟默3 小时前
Vue中watch监听属性的一些应用总结
前端·javascript·vue.js·watch
茶卡盐佑星_3 小时前
meta标签作用/SEO优化
前端·javascript·html
与衫3 小时前
掌握嵌套子查询:复杂 SQL 中 * 列的准确表列关系
android·javascript·sql
金灰3 小时前
HTML5--裸体回顾
java·开发语言·前端·javascript·html·html5