安装
$ npm install react-native-webview
复制代码
常规使用
作为一般的网页入口,传入 uri 链接。这里需要注意 android 环境下的 mixedContentMode,此参数允许加载 http 链接
<WebView
ref={ref => (this.webview = ref)}
source={{ uri: 'https://www.baidu.com/' }}
style={{ flex: 1 }}
mixedContentMode="compatibility" // Android: WebView 是否应该允许安全链接(https)页面中加载非安全链接(http)的内容,
/>
复制代码
作为登录入口场景
例如:一款 toB 的 app,面对很多家客户,每家客户都有自己的登录系统界面,并且客户要求接入自己的登录系统。
这个时候就需要 webview 接入登录界面之后,进行一些 “值拦截”,进行登录状态判断。这里主要用到 webview 的 onNavigationStateChange 参数。此方法会实时回调网页导航信息的变化,例如下面
{"canGoBack": false, "canGoForward": false, "loading": true, "navigationType": "other", "target": 229, "title": "", "url": "https://www.baidu.com/"}
复制代码
这里主要注意 url 字段,网页内部登录完成之后,可以发起一个重定向,前端关注 url 变化,进行登录状态的判断,同时重定向的 url 中可以拼接一些登录信息字段,用于前端登录状态校验等,例如:
{ "url": "https://www.baidu.com ? sessionId=xxx & username= xxx" }
复制代码
功能模块嵌入
将 webview 作为功能模块载体,这个时候就会涉及到用户交互,需要 rn 与 h5 进行值的互相传递。此时就要react native 向 web 中注入 js,web 也可以主动回传数据到 react native。
webview 组件提供了 injectedJavaScript 用于向 h5 注入js,在 h5 相关方法中使用 window.ReactNativeWebView.postMessage 可见进行主动的回调,并且在 webview 的 onMessage 中进行字段的监听,以此就可以完成 react 和 h5 的交互。
示例代码:
const injectJSStr = `
window.injectStr='我是注入的字段';
var div = document.getElementById('testID');
div.style.color='red';
div.style.fontSize='100px';
`;
const html = `
<html>
<head></head>
<body>
<script>
setTimeout(function () {
window.ReactNativeWebView.postMessage(window.injectStr)
}, 2000)
</script>
<div id='testID'>Hello Word</div>
</body>
</html>
`;
...
<View style={{flex: 1}}>
<WebView
source={{html}}
injectedJavaScript={injectJSStr}
onMessage={event => {
alert(event.nativeEvent.data);
}}
/>
</View>
复制代码
demo 中,webview 使用的是硬编码的 html,通过 injectedJavaScript主动注入 了一段字符串类型的js代码,并且 html 中主动回传注入的字段,使用 onMessage 来监听回传内容。
注:一般我进行 js 注入的时候,都会将参数或者方法挂载在window对象上。如果 h5 想暴露一些方法给 RN 以注入 js 的方式调用,也可以挂载在 window 上。
其他场景
从上一个示例中,扩展出来的业务场景,例如想使用 webview 显示 富文本,只需要向source字段赋值即可。
代码:DEMO
运行demo
$ git clone https://github.com/lianglei777/demos.git
$ cd demos
$ git checkout RNFaceDemo
$ cd RNFaceDemo
$ npm install
$ cd ios
$ pod install
复制代码
如果 pod install 失败,请参考 此文 的 cocoapods 部分。
有疑问请在评论区留言