创建hybrid.js
javascript
let hybrid = {
// 具体用到哪个写哪个?
isContainer: typeof container == 'object' && container,
isAndroid: /android/.test(UA),
isIOS: /iphone|ipad|ipod/.test(UA),
// 安卓客户端
isAndroidClient: /android/.test(UA) && typeof container != 'undefined' ,
// ios客户端
isIosClient: false,
// 用于判断是否是客户端
isClient() {
//XXX:app名字如happy就是/happy/i.test(UA)
return /XXX/i.test(UA) || hybrid.isAndroidClient || hybrid.isIosClient
},
// 是否是微信小程序
isMiniprogram() {
return UA.indexOf('miniprogram') > -1 && window.wx
},
}
javascript
hybrid.openScheme = function(scheme) {
const iframe = document.createElement('iframe');
iframe.setAttribute('id', 'iframe-scheme');
iframe.setAttribute('src', scheme);
iframe.setAttribute(
'style',
'position:absolute;z-index:-99999;top:0;right:0;bottom:0;left:-1000px;',
);
document.getElementsByTagName('body')[0].appendChild(iframe);
setTimeout(function() {
document.getElementById('iframe-scheme').remove();
}, 1000);
}
传递给端上方法
与端上IOS定义好方法,其中t=edit_app指的某个方法,from和title是参数
javascript
hybrid.editWeight = function(data) {
const {from,title } = data
hybrid.openScheme(`test-app://article?t=edit_app&from=1&title=${encodeURIComponent(title)}`)
}
//兼容安卓和IOS 的方法
javascript
hybrid.openTab = function() {
if (typeof container == 'object' && container && container.openTab) {
container.openTab();
} else {
hybrid.openScheme('test-app://article?t=open_tab');
}
}
javascript
export default hybrid
javascript
const [formData, setFormData] = useState([])
APP端给前端发送通知 直接发送传递
javascript
window.app.editApp = (参数)=> {}
react中直接
javascript
useEffect(() => {
console.log('process.env.UMI_ENV', process.env.UMI_ENV)
initList()
return () => {
}
}, [])
useEffect(() => {
initList()
}, [formData])
javascript
const initList = () =>{
window.app = window.app || {}
window.app.editApp = (v) => {
if (!v) return
try {
let data = JSON.parse(v)
// 对象的话
let newFormData = {}
for (let key in data) {
newFormData[key] = data[key]
}
// 数组
let newFormData = []
newFormData = data
setFormData(newFormData)
}
catch(e) { }
}
}