我這邊是有個需求要瀏覽的網(wǎng)頁實現(xiàn)圖片點擊放大,實現(xiàn)方法大概如下
添加接收onMessage
<WebView
...
source={{
html:changeHtmlTag(content)
}}
onMessage={event=>{
console.log('onMessage Result, ', event.nativeEvent, typeof event.nativeEvent.data)
if(checkImageUri(event.nativeEvent.data)){
//具體的點擊事件就放這里
setPressedImageUri(event.nativeEvent.data);
}
}}
...
/>
修改img標(biāo)簽加入傳出方法
const changeHtmlTag = (text) => {
let newText = text.replace(/<img /g, '<img onclick="image(this)" ');
return `
<script>
function image(img){
// alert(img.src);
// console.log('img after click', img);
window.ReactNativeWebView.postMessage(img.src)
}
</script>
${newText}
`;
}
檢測標(biāo)簽uri
const checkImageUri=(uri)=>{
return typeof uri==='string' && uri.includes('http');
}