1: 通过url获取平台,把平台名字拼在后面src/util/getUrlParameter
javascript复制代码function getUrlParameter(parameterName: string) {
// 获取url参数
const search = window.location.search.substring(1); // 获取查询字符串,去除问号字符"?"
const pairs = search.split(‘&’); // 将查询字符串分割成参数对
// eslint-disable-next-line no-plusplus
for (let i = 0; i < pairs.length; i++) {
const pair = pairs[i].split(‘=’);
const key = decodeURIComponent(pair[0]); // 解码参数名
const value = decodeURIComponent(pair[1]); // 解码参数值
// 如果参数名匹配,则返回对应的值
if (key === parameterName) {
return value;
}
}
// 如果未找到指定的参数名,则返回空
return ‘’;
}
export default getUrlParameter;
2:设置工具src/util/jsBridge
typescript复制代码 import mitt from ‘mitt’;
import { App } from ‘vue’;
import getUrlParameter from ‘./getUrlParameter’;
interface IPlatformArg {
type: string;
data: object;
}
const emitter = mitt();
const jsBridge = {
platformCall(obj: IPlatformArg) {},
install(app: App) {
this.getEntryBridge();
// eslint-disable-next-line no-param-reassign
app.config.globalProperties.jsBridge = this;
},
on(type: string, cb: (data:any) => void) {
emitter.on(type, cb);
},
off(type: string, cb?: (data:any) => void) {
if (cb) {
emitter.off(type, cb);
} else {
emitter.off(type);
}
},
emit(type: string, data: object) {
this.platformCall({ type, data });
},
getEntryBridge() {
// 抹平各插件调用方式
const platform = getUrlParameter(‘platform’);
if (platform === ‘androidStudio’) {
this.platformCall = (obj: IPlatformArg) => {
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
window.callStudio && window.callStudio(JSON.stringify(obj));
};
window.callWebview = (obj: IPlatformArg) => {
emitter.emit(obj.type, obj.data);
};
} else if (platform === ‘visualStudioCode’) {
this.platformCall = (obj: IPlatformArg) => {
console.log(‘platformCall’, obj);
window.parent.postMessage(obj, ‘*’);
};
window.addEventListener(‘message’, (e) => {
emitter.emit(e.data.type, e.data.data);
});
}
}
};
export default jsBridge;
3:在main.js安装
javascript复制代码import { createApp } from ‘vue’;
import App from ‘./App.vue’;
import jsBridge from ‘@/utils/jsBridge’;
const app = createApp(App);
app
.use(jsBridge)
.mount(‘#root’);
4:写hook,src/hooks/useJsBridge
javascript复制代码import { ComponentInternalInstance, getCurrentInstance } from ‘vue’;
export default function useJsBridge() {
const internalInstance = getCurrentInstance() as ComponentInternalInstance;
const { jsBridge } = internalInstance.appContext.config.globalProperties;
return jsBridge;
}
5:使用
javascript复制代码import useJsBridge from ‘./hooks/useJsBridge’;
const jsBridge = useJsBridge();
//监听插件的事件
jsBridge.on(‘和插件端约定好的事件’, (data) => {
//插件端传输的数据
console.log(data)
});
//webview传输给插件的数据
jsBridge.emit(‘和插件端约定好的事件’,{data});
//销毁事件,callback可不传代表销毁这个事件的所有回调
jsBridge.off(‘和插件端约定好的事件’,callback)