import {WebView} from 'react-native-webview';
import {useRef} from 'react';
const address = '<personal address>';
const injectedJavaScript = `
window.ethereum = {};
window.ethereum.isMetaMask = true;
window.ethereum.isConnected = function() {
console.log('-----------连接成功后调用---------')
return true
};
window.ethereum.wallet = {};
window.ethereum.wallet.address = '${address}';
window.ethereum.selectedAddress = '${address}';
window.ethereum.request = function(args = {}) {
console.log('---------Dapp交互触发该事件-----------', args)
const { method, params } = args
return window.ethereum.send(method, params)
};
window.ethereum.send = function(method, params) {
console.log('---------send-----------', method, params)
return new Promise(function(resolve, reject) {
window.ReactNativeWebView.postMessage(JSON.stringify({
type: 'bsc',
payload: {
method: method,
params: params,
}
}));
document.addEventListener("message", function(event) {
/**
* wallet端主动调用postMessage触发该事件
* 将webviewRef.current.postMessage回调的event.data作为Promise的值返回
*/
const data = JSON.parse(event.data) || {}
if (data.type === 'ethereum' && data.payload.id === method) {
if (data.payload.error) {
reject(data.payload.error);
} else {
resolve(data.payload.result);
}
}
}, { once: true });
});
};
`;
const BrowserTab = function () {
const webviewRef = useRef(null);
const handleWebViewMessage = async function (event: any) {
/**
* Dapp端交互调用window.ethereum.request时触发
* 根据window.ReactNativeWebView.postMessage传递的不同参数,返回对应的结果
*/
const {data} = event.nativeEvent;
const {type, payload = {}} = JSON.parse(data) || {};
const {method} = payload;
console.log(webviewRef.current);
if (webviewRef.current) {
method === 'eth_requestAccounts' &&
webviewRef.current.postMessage(
JSON.stringify({
type: 'ethereum',
payload: {
id: 'eth_requestAccounts',
result: [address],
},
}),
'*',
);
method === 'eth_chainId' &&
webviewRef.current.postMessage(
JSON.stringify({
type: 'ethereum',
payload: {
id: 'eth_chainId',
result: 5,
},
}),
'*',
);
}
};
return (
<WebView
ref={webviewRef}
source={{uri: 'https://app.uniswap.org/'}}
style={{flex: 1}}
javaScriptEnabled={true}
onMessage={handleWebViewMessage}
injectedJavaScriptBeforeContentLoaded={injectedJavaScript}
/>
);
};
export default BrowserTab;
11-26
378
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)