文章目录
- 一、WebView 组件介绍
- 二、WebView 使用样例
- 2.1 通过 url 地址加载网页
- 2.2 加载 html 代码
- 2.3 RN -> HTML5 通信
- 2.4 HTML5(Vue) -> RN 通信
- 2.5 JavaScript 脚本注入
- 三、拓展阅读
一、WebView 组件介绍
使用 WebView
组件可通过 url
来加载显示一个网页,也可以传入一段 html
代码来显示。下面对其主要属性和方法进行介绍。
1. 主要属性
-
source
:在WebView
中载入一段静态的html
代码或是一个url
(还可以附带一些header
选项); -
automaticallyAdjustContentInsets
:设置是否自动调整内容。格式:bool
; -
contentInset
:设置内容所占的尺寸大小。格式:{top:number,left:number,bottom:number,right:number};
-
injectJavaScript
:当网页加载之前注入一段js
代码。其值是字符串形式。 -
startInLoadingState
(默认值:无):是否开启页面加载的状态,其值为true
或者false
。 -
bounces
(仅iOS
,默认值:true
):回弹特性。如果设置为false
,则内容拉到底部或者头部都不回弹。 -
scalesPageToFit
(仅iOS
,默认值:true
):用于设置网页是否缩放自适应到整个屏幕视图,以及用户是否可以改变缩放页面。 -
scrollEnabled
(仅iOS
,默认值:true
):用于设置是否开启页面滚动。 -
domStorageEnabled
(仅Android
,默认值:true
):用于控制是否开启DOM Storage
(存储)。 -
javaScriptEnabled
(仅Android
,默认值:true
):是否开启JavaScript
,在iOS
中的WebView
是默认开启的。 -
useWebKit
:在react-native
开发中,从rn 0.37版本开始官方引入了组件,在安卓中调用原生浏览器,在IOS中默认调用的是UIWebView
容器。从IOS12开始,苹果正式弃用UIWebView
,统一采用WKWebView
。RN从0.57起,可指定使用WKWebView
作为WebView
的实现
2. 主要方法
-
onNavigationStateChange
:当导航状态发生变化的时候调用。 -
onLoadStart
:当网页开始加载的时候调用。 -
onError
:当网页加载失败的时候调用。 -
onLoad
:当网页加载结束的时候调用。 -
onLoadEnd
:当网页加载结束调用,不管是成功还是失败。 -
renderLoading
:WebView
组件正在渲染页面时触发的函数,只有startInLoadingState
为true
时该函数才起作用。 -
renderError
:监听渲染页面出错回调函数。 -
onShouldStartLoadWithRequest
(仅iOS
):该方法允许拦截WebView
加载的 URL 地址,进行自定义处理。该方法通过返回true
或者false
来决定是否继续加载该拦截到请求。 -
onMessage
:在webView
内部网页中,调用可以触发此属性对应的函数,通过
获取接收到的数据,实现网页和
RN
之间的数据传递。 -
injectJavaScript
:函数接受一个字符串,该字符串将传递给WebView
,并立即执行为JavaScript
。
二、WebView 使用样例
2.1 通过 url 地址加载网页
import React, {Component} from 'react';
import {
AppRegistry,
StyleSheet,
Dimensions,
Text,
View,
WebView
} from 'react-native';
//获取设备的宽度和高度
var {
height: deviceHeight,
width: deviceWidth
} = Dimensions.get('window');
//默认应用的容器组件
class App extends Component {
//渲染
render() {
return (
<View style={styles.container}>
<WebView bounces={false}
scalesPageToFit={true}
source={{uri:"/",method: 'GET'}}
style={{width:deviceWidth, height:deviceHeight}}>
</WebView>
</View>
);
}
}
//样式定义
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop:20
}
});
AppRegistry.registerComponent('HelloWorld', () => App);
2.2 加载 html 代码
import React, {Component} from 'react';
import {
AppRegistry,
StyleSheet,
Dimensions,
Text,
View,
WebView
} from 'react-native';
//获取设备的宽度和高度
var {
height: deviceHeight,
width: deviceWidth
} = Dimensions.get('window');
//默认应用的容器组件
class App extends Component {
//渲染
render() {
return (
<View style={styles.container}>
<WebView bounces={false}
scalesPageToFit={true}
source={{html:"<h1 style='color:#ff0000'>欢迎访问 /</h1>"}}
style={{width:deviceWidth, height:deviceHeight}}>
</WebView>
</View>
);
}
}
//样式定义
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop:20
}
});
AppRegistry.registerComponent('HelloWorld', () => App);
2.3 RN -> HTML5 通信
当WebView
加载html
时,可实现html
和rn
之间的通信。rn
向html
发送数据可以通过postMessage
函数实现。如下:
RN
<WebView
ref={(view) => (this.webView = view)}
useWebKit={false}
onLoad={() => {
let data = {
name: userInfo.usrName
};
this.webView.postMessage(JSON.stringify(data));
}}
onError={(event) => {
console.log(`==webViewError:${JSON.stringify(event.nativeEvent)}`);
}}
onMessage={(event) => {
this._onH5Message(event);
}}
automaticallyAdjustContentInsets={false}
contentInset={{ top: 0, left: 0, bottom: -1, right: 0 }}
onScroll={(event) => this._onScroll(event)}
style={styles.webview}
source={this.html ? { html: this.html } : { uri: this.url }}
bounces={false}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
/>
html
// 在html中注册事件接收rn发过来的数据并显示在html中
document.addEventListener('message', function listener(RnData) {
messagesReceivedFromReactNative += 1;
document.getElementsByTagName('p')[0].innerHTML =
'从React Native接收的消息: ' + messagesReceivedFromReactNative;
document.getElementsByTagName('p')[1].innerHTML = RnData.data;
// 获取接收后的数据后,及时清除监听器
document.removeEventListener('message', listener)
});
在html
中定义一个按钮,并添加事件向rn
发送数据:
//向rn发送数据
document.getElementsByTagName('button')[0].addEventListener('click', function() {
window.postMessage('这是html发送到RN的消息');
});
当html
中调用了函数后,
WebView
的onMessage
函数将会被回调,用来处理html
向rn
发送的数据,可以通过获取发送过来的数据。
// 接收HTML发出的数据
_onH5Message = (e) => {
this.setState({
messagesReceivedFromWebView: this.state.messagesReceivedFromWebView + 1,
message: e.nativeEvent.data,
})
Alert.alert(e.nativeEvent.data)
}
2.4 HTML5(Vue) -> RN 通信
HTML5
const message = {
flag: 'previewIamge'
filePath: filePath
}
window.ReactNativeWebView.postMessage(Json.stringify(message))
RN
还是通过WebView
提供的onMessage
属性完成回调。
<WebView
ref={(view) => (this.webView = view)}
useWebKit={false}
onLoad={() => {
let data = {
name: userInfo.usrName
};
this.webView.postMessage(JSON.stringify(data));
}}
onError={(event) => {
console.log(`==webViewError:${JSON.stringify(event.nativeEvent)}`);
}}
onMessage={(event) => {
this._onH5Message(event);
}}
automaticallyAdjustContentInsets={false}
contentInset={{ top: 0, left: 0, bottom: -1, right: 0 }}
onScroll={(event) => this._onScroll(event)}
style={styles.webview}
source={this.html ? { html: this.html } : { uri: this.url }}
bounces={false}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
/>
回调函数_onH5Message()
实现逻辑如下:
// 接收HTML发出的数据
_onH5Message = (e) => {
this.setState({
messagesReceivedFromWebView: this.state.messagesReceivedFromWebView + 1,
message: e.nativeEvent.data,
})
Alert.alert(e.nativeEvent.data)
}
2.5 JavaScript 脚本注入
注:这种方式适用于
react-native-webview
(RN
本身没有试过)。
在android
开发中,需要使用 javaScriptEnabled
属性来支持JavaScript
,ios
默认是支持的,没有此属性。在WebView
中提供了函数injectJavaScript(String)
,它有一个字符串参数,可以向webview
中注入脚本,如下:
//脚本注入
injectJS = () => {
const script = '("Injected JS ")'; // eslint-disable-line quotes
if (this.webview) {
this.webview.injectJavaScript(script);
}
}
实现思路:通过injectJavaScript
注入JS
,在H5
页面加载之后立即执行。相当于webview
端主动调用H5
的方法。
注意事项:injectJavaScript
注入的必须是js
。注入内容可以是方法实现,也可以是方法名字。
注意:
- 注入函数名的时候,实际上注入的仍然是函数实现。
- 当注入
js
方法名需要传递参数的时候,可提前将函数名作为字符串,函数参数作为变量,生成一个字符串,然后将此字符串注入。
RN端
首先Webview
绑定 ref='webView'
在H5
调用一个名为 receiveMessage
的函数,并传入一个字符串, 参数true不可少
<WebView
ref={(view) => (this.webView = view)}
useWebKit={false}
onLoadEnd={() => {
this.endLoad();
}}
..
/>
//加载结束调用,不管是成功还是失败。
endLoad(){
// 在H5调用一个名为 `receiveMessage` 的函数,并传入一个字符串, 参数true不可少
this.refs.webView.injectJavaScript(`receiveMessage("RN向H5发送消息");true;`)
}
H5端(Vue实现)
mounted
中往 window
上添加一个方法(注意:不是监听,只是挂载);名为 receiveMessage
(必须和RN
端保持一致)。
mounted(){
//在window上挂载一个receiveMessage方法,RN会调用
window.receiveMessage = (msg) => {
alert( msg)
}
},
三、拓展阅读
- WebView 官方文档