🦅 WIP: Update to WKWebView - Replace UIWebView with WKWebView
This commit is contained in:
parent
86ec597ea2
commit
52fbf09e29
|
@ -1,482 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var React = require('react');
|
||||
var ReactNative = require('react-native');
|
||||
var {
|
||||
StyleSheet,
|
||||
Text,
|
||||
TextInput,
|
||||
TouchableWithoutFeedback,
|
||||
TouchableOpacity,
|
||||
View,
|
||||
WebView,
|
||||
} = ReactNative;
|
||||
|
||||
var HEADER = '#3b5998';
|
||||
var BGWASH = 'rgba(255,255,255,0.8)';
|
||||
var DISABLED_WASH = 'rgba(255,255,255,0.25)';
|
||||
|
||||
var TEXT_INPUT_REF = 'urlInput';
|
||||
var WEBVIEW_REF = 'webview';
|
||||
var DEFAULT_URL = 'https://m.facebook.com';
|
||||
const FILE_SYSTEM_ORIGIN_WHITE_LIST = ['file://*', 'http://*', 'https://*'];
|
||||
|
||||
class WebViewExample extends React.Component {
|
||||
state = {
|
||||
url: DEFAULT_URL,
|
||||
status: 'No Page Loaded',
|
||||
backButtonEnabled: false,
|
||||
forwardButtonEnabled: false,
|
||||
loading: true,
|
||||
scalesPageToFit: true,
|
||||
};
|
||||
|
||||
inputText = '';
|
||||
|
||||
handleTextInputChange = event => {
|
||||
var url = event.nativeEvent.text;
|
||||
if (!/^[a-zA-Z-_]+:/.test(url)) {
|
||||
url = 'http://' + url;
|
||||
}
|
||||
this.inputText = url;
|
||||
};
|
||||
|
||||
render() {
|
||||
this.inputText = this.state.url;
|
||||
|
||||
return (
|
||||
<View style={[styles.container]}>
|
||||
<View style={[styles.addressBarRow]}>
|
||||
<TouchableOpacity
|
||||
onPress={this.goBack}
|
||||
style={
|
||||
this.state.backButtonEnabled
|
||||
? styles.navButton
|
||||
: styles.disabledButton
|
||||
}>
|
||||
<Text>{'<'}</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity
|
||||
onPress={this.goForward}
|
||||
style={
|
||||
this.state.forwardButtonEnabled
|
||||
? styles.navButton
|
||||
: styles.disabledButton
|
||||
}>
|
||||
<Text>{'>'}</Text>
|
||||
</TouchableOpacity>
|
||||
<TextInput
|
||||
ref={TEXT_INPUT_REF}
|
||||
autoCapitalize="none"
|
||||
defaultValue={this.state.url}
|
||||
onSubmitEditing={this.onSubmitEditing}
|
||||
onChange={this.handleTextInputChange}
|
||||
clearButtonMode="while-editing"
|
||||
style={styles.addressBarTextInput}
|
||||
/>
|
||||
<TouchableOpacity onPress={this.pressGoButton}>
|
||||
<View style={styles.goButton}>
|
||||
<Text>Go!</Text>
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
<WebView
|
||||
ref={WEBVIEW_REF}
|
||||
automaticallyAdjustContentInsets={false}
|
||||
style={styles.webView}
|
||||
source={{ uri: this.state.url }}
|
||||
javaScriptEnabled={true}
|
||||
domStorageEnabled={true}
|
||||
decelerationRate="normal"
|
||||
onNavigationStateChange={this.onNavigationStateChange}
|
||||
onShouldStartLoadWithRequest={this.onShouldStartLoadWithRequest}
|
||||
startInLoadingState={true}
|
||||
scalesPageToFit={this.state.scalesPageToFit}
|
||||
/>
|
||||
<View style={styles.statusBar}>
|
||||
<Text style={styles.statusBarText}>{this.state.status}</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
goBack = () => {
|
||||
this.refs[WEBVIEW_REF].goBack();
|
||||
};
|
||||
|
||||
goForward = () => {
|
||||
this.refs[WEBVIEW_REF].goForward();
|
||||
};
|
||||
|
||||
reload = () => {
|
||||
this.refs[WEBVIEW_REF].reload();
|
||||
};
|
||||
|
||||
onShouldStartLoadWithRequest = event => {
|
||||
// Implement any custom loading logic here, don't forget to return!
|
||||
return true;
|
||||
};
|
||||
|
||||
onNavigationStateChange = navState => {
|
||||
this.setState({
|
||||
backButtonEnabled: navState.canGoBack,
|
||||
forwardButtonEnabled: navState.canGoForward,
|
||||
url: navState.url,
|
||||
status: navState.title,
|
||||
loading: navState.loading,
|
||||
scalesPageToFit: true,
|
||||
});
|
||||
};
|
||||
|
||||
onSubmitEditing = event => {
|
||||
this.pressGoButton();
|
||||
};
|
||||
|
||||
pressGoButton = () => {
|
||||
var url = this.inputText.toLowerCase();
|
||||
if (url === this.state.url) {
|
||||
this.reload();
|
||||
} else {
|
||||
this.setState({
|
||||
url: url,
|
||||
});
|
||||
}
|
||||
// dismiss keyboard
|
||||
this.refs[TEXT_INPUT_REF].blur();
|
||||
};
|
||||
}
|
||||
|
||||
class Button extends React.Component {
|
||||
_handlePress = () => {
|
||||
if (this.props.enabled !== false && this.props.onPress) {
|
||||
this.props.onPress();
|
||||
}
|
||||
};
|
||||
|
||||
render() {
|
||||
return (
|
||||
<TouchableWithoutFeedback onPress={this._handlePress}>
|
||||
<View style={styles.button}>
|
||||
<Text>{this.props.text}</Text>
|
||||
</View>
|
||||
</TouchableWithoutFeedback>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ScaledWebView extends React.Component {
|
||||
state = {
|
||||
scalingEnabled: true,
|
||||
};
|
||||
|
||||
render() {
|
||||
return (
|
||||
<View>
|
||||
<WebView
|
||||
style={{
|
||||
backgroundColor: BGWASH,
|
||||
height: 200,
|
||||
}}
|
||||
source={{ uri: 'https://facebook.github.io/react/' }}
|
||||
scalesPageToFit={this.state.scalingEnabled}
|
||||
/>
|
||||
<View style={styles.buttons}>
|
||||
{this.state.scalingEnabled ? (
|
||||
<Button
|
||||
text="Scaling:ON"
|
||||
enabled={true}
|
||||
onPress={() => this.setState({ scalingEnabled: false })}
|
||||
/>
|
||||
) : (
|
||||
<Button
|
||||
text="Scaling:OFF"
|
||||
enabled={true}
|
||||
onPress={() => this.setState({ scalingEnabled: true })}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class MessagingTest extends React.Component {
|
||||
webview = null;
|
||||
|
||||
state = {
|
||||
messagesReceivedFromWebView: 0,
|
||||
message: '',
|
||||
};
|
||||
|
||||
onMessage = e =>
|
||||
this.setState({
|
||||
messagesReceivedFromWebView: this.state.messagesReceivedFromWebView + 1,
|
||||
message: e.nativeEvent.data,
|
||||
});
|
||||
|
||||
postMessage = () => {
|
||||
if (this.webview) {
|
||||
this.webview.postMessage('"Hello" from React Native!');
|
||||
}
|
||||
};
|
||||
|
||||
render() {
|
||||
const { messagesReceivedFromWebView, message } = this.state;
|
||||
|
||||
return (
|
||||
<View style={[styles.container, { height: 200 }]}>
|
||||
<View style={styles.container}>
|
||||
<Text>
|
||||
Messages received from web view: {messagesReceivedFromWebView}
|
||||
</Text>
|
||||
<Text>{message || '(No message)'}</Text>
|
||||
<View style={styles.buttons}>
|
||||
<Button
|
||||
text="Send Message to Web View"
|
||||
enabled
|
||||
onPress={this.postMessage}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.container}>
|
||||
<WebView
|
||||
ref={webview => {
|
||||
this.webview = webview;
|
||||
}}
|
||||
style={{
|
||||
backgroundColor: BGWASH,
|
||||
height: 100,
|
||||
}}
|
||||
originWhitelist={FILE_SYSTEM_ORIGIN_WHITE_LIST}
|
||||
source={require('./messagingtest.html')}
|
||||
onMessage={this.onMessage}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class InjectJS extends React.Component {
|
||||
webview = null;
|
||||
injectJS = () => {
|
||||
const script = 'document.write("Injected JS ")';
|
||||
if (this.webview) {
|
||||
this.webview.injectJavaScript(script);
|
||||
}
|
||||
};
|
||||
render() {
|
||||
return (
|
||||
<View>
|
||||
<WebView
|
||||
ref={webview => {
|
||||
this.webview = webview;
|
||||
}}
|
||||
style={{
|
||||
backgroundColor: BGWASH,
|
||||
height: 300,
|
||||
}}
|
||||
source={{ uri: 'https://www.facebook.com' }}
|
||||
scalesPageToFit={true}
|
||||
/>
|
||||
<View style={styles.buttons}>
|
||||
<Button text="Inject JS" enabled onPress={this.injectJS} />
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
var styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: HEADER,
|
||||
},
|
||||
addressBarRow: {
|
||||
flexDirection: 'row',
|
||||
padding: 8,
|
||||
},
|
||||
webView: {
|
||||
backgroundColor: BGWASH,
|
||||
height: 350,
|
||||
},
|
||||
addressBarTextInput: {
|
||||
backgroundColor: BGWASH,
|
||||
borderColor: 'transparent',
|
||||
borderRadius: 3,
|
||||
borderWidth: 1,
|
||||
height: 24,
|
||||
paddingLeft: 10,
|
||||
paddingTop: 3,
|
||||
paddingBottom: 3,
|
||||
flex: 1,
|
||||
fontSize: 14,
|
||||
},
|
||||
navButton: {
|
||||
width: 20,
|
||||
padding: 3,
|
||||
marginRight: 3,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
backgroundColor: BGWASH,
|
||||
borderColor: 'transparent',
|
||||
borderRadius: 3,
|
||||
},
|
||||
disabledButton: {
|
||||
width: 20,
|
||||
padding: 3,
|
||||
marginRight: 3,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
backgroundColor: DISABLED_WASH,
|
||||
borderColor: 'transparent',
|
||||
borderRadius: 3,
|
||||
},
|
||||
goButton: {
|
||||
height: 24,
|
||||
padding: 3,
|
||||
marginLeft: 8,
|
||||
alignItems: 'center',
|
||||
backgroundColor: BGWASH,
|
||||
borderColor: 'transparent',
|
||||
borderRadius: 3,
|
||||
alignSelf: 'stretch',
|
||||
},
|
||||
statusBar: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
paddingLeft: 5,
|
||||
height: 22,
|
||||
},
|
||||
statusBarText: {
|
||||
color: 'white',
|
||||
fontSize: 13,
|
||||
},
|
||||
spinner: {
|
||||
width: 20,
|
||||
marginRight: 6,
|
||||
},
|
||||
buttons: {
|
||||
flexDirection: 'row',
|
||||
height: 30,
|
||||
backgroundColor: 'black',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
},
|
||||
button: {
|
||||
flex: 0.5,
|
||||
width: 0,
|
||||
margin: 5,
|
||||
borderColor: 'gray',
|
||||
borderWidth: 1,
|
||||
backgroundColor: 'gray',
|
||||
},
|
||||
});
|
||||
|
||||
const HTML = `
|
||||
<!DOCTYPE html>\n
|
||||
<html>
|
||||
<head>
|
||||
<title>Hello Static World</title>
|
||||
<meta http-equiv="content-type" content="text/html; charset=utf-8">
|
||||
<meta name="viewport" content="width=320, user-scalable=no">
|
||||
<style type="text/css">
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font: 62.5% arial, sans-serif;
|
||||
background: #ccc;
|
||||
}
|
||||
h1 {
|
||||
padding: 45px;
|
||||
margin: 0;
|
||||
text-align: center;
|
||||
color: #33f;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hello Static World</h1>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
|
||||
exports.displayName = undefined;
|
||||
exports.title = '<WebView>';
|
||||
exports.description = 'Base component to display web content';
|
||||
exports.examples = [
|
||||
{
|
||||
title: 'Simple Browser',
|
||||
render() {
|
||||
return <WebViewExample />;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: 'Scale Page to Fit',
|
||||
render() {
|
||||
return <ScaledWebView />;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: 'Bundled HTML',
|
||||
render() {
|
||||
return (
|
||||
<WebView
|
||||
style={{
|
||||
backgroundColor: BGWASH,
|
||||
height: 100,
|
||||
}}
|
||||
originWhitelist={FILE_SYSTEM_ORIGIN_WHITE_LIST}
|
||||
source={require('./helloworld.html')}
|
||||
scalesPageToFit={true}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: 'Static HTML',
|
||||
render() {
|
||||
return (
|
||||
<WebView
|
||||
style={{
|
||||
backgroundColor: BGWASH,
|
||||
height: 100,
|
||||
}}
|
||||
source={{ html: HTML }}
|
||||
scalesPageToFit={true}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: 'POST Test',
|
||||
render() {
|
||||
return (
|
||||
<WebView
|
||||
style={{
|
||||
backgroundColor: BGWASH,
|
||||
height: 100,
|
||||
}}
|
||||
source={{
|
||||
uri: 'http://www.posttestserver.com/post.php',
|
||||
method: 'POST',
|
||||
body: 'foo=bar&bar=foo',
|
||||
}}
|
||||
scalesPageToFit={false}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: 'Messaging Test',
|
||||
render() {
|
||||
return <MessagingTest />;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: 'Inject JavaScript',
|
||||
render() {
|
||||
return <InjectJS />;
|
||||
},
|
||||
},
|
||||
];
|
|
@ -1,134 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var React = require('react');
|
||||
var ReactNative = require('react-native');
|
||||
var { StyleSheet, Text, TouchableHighlight, View, WebView } = ReactNative;
|
||||
|
||||
var RCTNetworking = require('RCTNetworking');
|
||||
|
||||
class XHRExampleCookies extends React.Component<any, any> {
|
||||
cancelled: boolean;
|
||||
|
||||
constructor(props: any) {
|
||||
super(props);
|
||||
this.cancelled = false;
|
||||
this.state = {
|
||||
status: '',
|
||||
a: 1,
|
||||
b: 2,
|
||||
};
|
||||
}
|
||||
|
||||
setCookie(domain: string) {
|
||||
var { a, b } = this.state;
|
||||
var url = `https://${domain}/cookies/set?a=${a}&b=${b}`;
|
||||
fetch(url).then(response => {
|
||||
this.setStatus(`Cookies a=${a}, b=${b} set`);
|
||||
this.refreshWebview();
|
||||
});
|
||||
|
||||
this.setState({
|
||||
status: 'Setting cookies...',
|
||||
a: a + 1,
|
||||
b: b + 2,
|
||||
});
|
||||
}
|
||||
|
||||
getCookies(domain: string) {
|
||||
fetch(`https://${domain}/cookies`)
|
||||
.then(response => {
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
this.setStatus(
|
||||
`Got cookies ${JSON.stringify(data.cookies)} from server`,
|
||||
);
|
||||
this.refreshWebview();
|
||||
});
|
||||
|
||||
this.setStatus('Getting cookies...');
|
||||
}
|
||||
|
||||
clearCookies() {
|
||||
RCTNetworking.clearCookies(cleared => {
|
||||
this.setStatus('Cookies cleared, had cookies=' + cleared.toString());
|
||||
this.refreshWebview();
|
||||
});
|
||||
}
|
||||
|
||||
refreshWebview() {
|
||||
this.refs.webview.reload();
|
||||
}
|
||||
|
||||
setStatus(status: string) {
|
||||
this.setState({ status });
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<View>
|
||||
<TouchableHighlight
|
||||
style={styles.wrapper}
|
||||
onPress={this.setCookie.bind(this, 'httpbin.org')}>
|
||||
<View style={styles.button}>
|
||||
<Text>Set cookie</Text>
|
||||
</View>
|
||||
</TouchableHighlight>
|
||||
<TouchableHighlight
|
||||
style={styles.wrapper}
|
||||
onPress={this.setCookie.bind(this, 'eu.httpbin.org')}>
|
||||
<View style={styles.button}>
|
||||
<Text>Set cookie (EU)</Text>
|
||||
</View>
|
||||
</TouchableHighlight>
|
||||
<TouchableHighlight
|
||||
style={styles.wrapper}
|
||||
onPress={this.getCookies.bind(this, 'httpbin.org')}>
|
||||
<View style={styles.button}>
|
||||
<Text>Get cookies</Text>
|
||||
</View>
|
||||
</TouchableHighlight>
|
||||
<TouchableHighlight
|
||||
style={styles.wrapper}
|
||||
onPress={this.getCookies.bind(this, 'eu.httpbin.org')}>
|
||||
<View style={styles.button}>
|
||||
<Text>Get cookies (EU)</Text>
|
||||
</View>
|
||||
</TouchableHighlight>
|
||||
<TouchableHighlight
|
||||
style={styles.wrapper}
|
||||
onPress={this.clearCookies.bind(this)}>
|
||||
<View style={styles.button}>
|
||||
<Text>Clear cookies</Text>
|
||||
</View>
|
||||
</TouchableHighlight>
|
||||
<Text>{this.state.status}</Text>
|
||||
<TouchableHighlight
|
||||
style={styles.wrapper}
|
||||
onPress={this.refreshWebview.bind(this)}>
|
||||
<View style={styles.button}>
|
||||
<Text>Refresh Webview</Text>
|
||||
</View>
|
||||
</TouchableHighlight>
|
||||
<WebView
|
||||
ref="webview"
|
||||
source={{ uri: 'http://httpbin.org/cookies' }}
|
||||
style={{ height: 100 }}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
var styles = StyleSheet.create({
|
||||
wrapper: {
|
||||
borderRadius: 5,
|
||||
marginBottom: 5,
|
||||
},
|
||||
button: {
|
||||
backgroundColor: '#eeeeee',
|
||||
padding: 8,
|
||||
},
|
||||
});
|
||||
|
||||
module.exports = XHRExampleCookies;
|
|
@ -0,0 +1,46 @@
|
|||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
#import <React/RCTView.h>
|
||||
#import <React/RCTDefines.h>
|
||||
#import <WebKit/WebKit.h>
|
||||
|
||||
@class RCTWKWebView;
|
||||
|
||||
@protocol RCTWKWebViewDelegate <NSObject>
|
||||
|
||||
- (BOOL)webView:(RCTWKWebView *)webView
|
||||
shouldStartLoadForRequest:(NSMutableDictionary<NSString *, id> *)request
|
||||
withCallback:(RCTDirectEventBlock)callback;
|
||||
|
||||
@end
|
||||
|
||||
@interface RCTWKWebView : RCTView
|
||||
|
||||
@property (nonatomic, weak) id<RCTWKWebViewDelegate> delegate;
|
||||
@property (nonatomic, copy) NSDictionary *source;
|
||||
@property (nonatomic, assign) BOOL messagingEnabled;
|
||||
@property (nonatomic, copy) NSString *injectedJavaScript;
|
||||
@property (nonatomic, assign) BOOL scrollEnabled;
|
||||
@property (nonatomic, assign) CGFloat decelerationRate;
|
||||
@property (nonatomic, assign) BOOL allowsInlineMediaPlayback;
|
||||
@property (nonatomic, assign) BOOL bounces;
|
||||
@property (nonatomic, assign) BOOL mediaPlaybackRequiresUserAction;
|
||||
#if WEBKIT_IOS_10_APIS_AVAILABLE
|
||||
@property (nonatomic, assign) WKDataDetectorTypes dataDetectorTypes;
|
||||
#endif
|
||||
@property (nonatomic, assign) UIEdgeInsets contentInset;
|
||||
@property (nonatomic, assign) BOOL automaticallyAdjustContentInsets;
|
||||
|
||||
- (void)postMessage:(NSString *)message;
|
||||
- (void)injectJavaScript:(NSString *)script;
|
||||
- (void)goForward;
|
||||
- (void)goBack;
|
||||
- (void)reload;
|
||||
- (void)stopLoading;
|
||||
|
||||
@end
|
|
@ -0,0 +1,412 @@
|
|||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
#import "RCTWKWebView.h"
|
||||
#import <React/RCTConvert.h>
|
||||
#import <React/RCTAutoInsetsProtocol.h>
|
||||
|
||||
static NSString *const MessageHanderName = @"ReactNative";
|
||||
|
||||
@interface RCTWKWebView () <WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler, UIScrollViewDelegate, RCTAutoInsetsProtocol>
|
||||
@property (nonatomic, copy) RCTDirectEventBlock onLoadingStart;
|
||||
@property (nonatomic, copy) RCTDirectEventBlock onLoadingFinish;
|
||||
@property (nonatomic, copy) RCTDirectEventBlock onLoadingError;
|
||||
@property (nonatomic, copy) RCTDirectEventBlock onShouldStartLoadWithRequest;
|
||||
@property (nonatomic, copy) RCTDirectEventBlock onMessage;
|
||||
@property (nonatomic, copy) WKWebView *webView;
|
||||
@end
|
||||
|
||||
@implementation RCTWKWebView
|
||||
{
|
||||
UIColor * _savedBackgroundColor;
|
||||
}
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* See https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DisplayWebContent/Tasks/WebKitAvail.html.
|
||||
*/
|
||||
+ (BOOL)dynamicallyLoadWebKitIfAvailable
|
||||
{
|
||||
static BOOL _webkitAvailable=NO;
|
||||
static dispatch_once_t onceToken;
|
||||
|
||||
dispatch_once(&onceToken, ^{
|
||||
NSBundle *webKitBundle = [NSBundle bundleWithPath:@"/System/Library/Frameworks/WebKit.framework"];
|
||||
if (webKitBundle) {
|
||||
_webkitAvailable = [webKitBundle load];
|
||||
}
|
||||
});
|
||||
|
||||
return _webkitAvailable;
|
||||
}
|
||||
|
||||
|
||||
- (instancetype)initWithFrame:(CGRect)frame
|
||||
{
|
||||
if ((self = [super initWithFrame:frame])) {
|
||||
super.backgroundColor = [UIColor clearColor];
|
||||
_bounces = YES;
|
||||
_scrollEnabled = YES;
|
||||
_automaticallyAdjustContentInsets = YES;
|
||||
_contentInset = UIEdgeInsetsZero;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)didMoveToWindow
|
||||
{
|
||||
if (self.window != nil) {
|
||||
if (![[self class] dynamicallyLoadWebKitIfAvailable]) {
|
||||
return;
|
||||
};
|
||||
|
||||
WKWebViewConfiguration *wkWebViewConfig = [WKWebViewConfiguration new];
|
||||
wkWebViewConfig.userContentController = [WKUserContentController new];
|
||||
[wkWebViewConfig.userContentController addScriptMessageHandler: self name: MessageHanderName];
|
||||
wkWebViewConfig.allowsInlineMediaPlayback = _allowsInlineMediaPlayback;
|
||||
#if WEBKIT_IOS_10_APIS_AVAILABLE
|
||||
wkWebViewConfig.mediaTypesRequiringUserActionForPlayback = _mediaPlaybackRequiresUserAction
|
||||
? WKAudiovisualMediaTypeAll
|
||||
: WKAudiovisualMediaTypeNone;
|
||||
wkWebViewConfig.dataDetectorTypes = _dataDetectorTypes;
|
||||
#endif
|
||||
|
||||
_webView = [[WKWebView alloc] initWithFrame:self.bounds configuration: wkWebViewConfig];
|
||||
_webView.scrollView.delegate = self;
|
||||
_webView.UIDelegate = self;
|
||||
_webView.navigationDelegate = self;
|
||||
_webView.scrollView.scrollEnabled = _scrollEnabled;
|
||||
_webView.scrollView.bounces = _bounces;
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
|
||||
if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
|
||||
_webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
|
||||
}
|
||||
#endif
|
||||
|
||||
[self addSubview:_webView];
|
||||
|
||||
[self visitSource];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setBackgroundColor:(UIColor *)backgroundColor
|
||||
{
|
||||
_savedBackgroundColor = backgroundColor;
|
||||
if (_webView == nil) {
|
||||
return;
|
||||
}
|
||||
|
||||
CGFloat alpha = CGColorGetAlpha(backgroundColor.CGColor);
|
||||
self.opaque = _webView.opaque = (alpha == 1.0);
|
||||
_webView.scrollView.backgroundColor = backgroundColor;
|
||||
_webView.backgroundColor = backgroundColor;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is called whenever JavaScript running within the web view calls:
|
||||
* - window.webkit.messageHandlers.[MessageHanderName].postMessage
|
||||
*/
|
||||
- (void)userContentController:(WKUserContentController *)userContentController
|
||||
didReceiveScriptMessage:(WKScriptMessage *)message
|
||||
{
|
||||
if (_onMessage != nil) {
|
||||
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
|
||||
[event addEntriesFromDictionary: @{@"data": message.body}];
|
||||
_onMessage(event);
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setSource:(NSDictionary *)source
|
||||
{
|
||||
if (![_source isEqualToDictionary:source]) {
|
||||
_source = [source copy];
|
||||
|
||||
if (_webView != nil) {
|
||||
[self visitSource];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setContentInset:(UIEdgeInsets)contentInset
|
||||
{
|
||||
_contentInset = contentInset;
|
||||
[RCTView autoAdjustInsetsForView:self
|
||||
withScrollView:_webView.scrollView
|
||||
updateOffset:NO];
|
||||
}
|
||||
|
||||
- (void)refreshContentInset
|
||||
{
|
||||
[RCTView autoAdjustInsetsForView:self
|
||||
withScrollView:_webView.scrollView
|
||||
updateOffset:YES];
|
||||
}
|
||||
|
||||
- (void)visitSource
|
||||
{
|
||||
// Check for a static html source first
|
||||
NSString *html = [RCTConvert NSString:_source[@"html"]];
|
||||
if (html) {
|
||||
NSURL *baseURL = [RCTConvert NSURL:_source[@"baseUrl"]];
|
||||
if (!baseURL) {
|
||||
baseURL = [NSURL URLWithString:@"about:blank"];
|
||||
}
|
||||
[_webView loadHTMLString:html baseURL:baseURL];
|
||||
return;
|
||||
}
|
||||
|
||||
NSURLRequest *request = [RCTConvert NSURLRequest:_source];
|
||||
// Because of the way React works, as pages redirect, we actually end up
|
||||
// passing the redirect urls back here, so we ignore them if trying to load
|
||||
// the same url. We'll expose a call to 'reload' to allow a user to load
|
||||
// the existing page.
|
||||
if ([request.URL isEqual:_webView.URL]) {
|
||||
return;
|
||||
}
|
||||
if (!request.URL) {
|
||||
// Clear the webview
|
||||
[_webView loadHTMLString:@"" baseURL:nil];
|
||||
return;
|
||||
}
|
||||
[_webView loadRequest:request];
|
||||
}
|
||||
|
||||
|
||||
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
|
||||
{
|
||||
scrollView.decelerationRate = _decelerationRate;
|
||||
}
|
||||
|
||||
- (void)setScrollEnabled:(BOOL)scrollEnabled
|
||||
{
|
||||
_scrollEnabled = scrollEnabled;
|
||||
_webView.scrollView.scrollEnabled = scrollEnabled;
|
||||
}
|
||||
|
||||
- (void)postMessage:(NSString *)message
|
||||
{
|
||||
NSDictionary *eventInitDict = @{@"data": message};
|
||||
NSString *source = [NSString
|
||||
stringWithFormat:@"document.dispatchEvent(new MessageEvent('message', %@));",
|
||||
RCTJSONStringify(eventInitDict, NULL)
|
||||
];
|
||||
[self evaluateJS: source thenCall: nil];
|
||||
}
|
||||
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
[super layoutSubviews];
|
||||
|
||||
// Ensure webview takes the position and dimensions of RCTWKWebView
|
||||
_webView.frame = self.bounds;
|
||||
}
|
||||
|
||||
- (NSMutableDictionary<NSString *, id> *)baseEvent
|
||||
{
|
||||
NSDictionary *event = @{
|
||||
@"url": _webView.URL.absoluteString ?: @"",
|
||||
@"title": _webView.title,
|
||||
@"loading" : @(_webView.loading),
|
||||
@"canGoBack": @(_webView.canGoBack),
|
||||
@"canGoForward" : @(_webView.canGoForward)
|
||||
};
|
||||
return [[NSMutableDictionary alloc] initWithDictionary: event];
|
||||
}
|
||||
|
||||
#pragma mark - WKNavigationDelegate methods
|
||||
|
||||
/**
|
||||
* Decides whether to allow or cancel a navigation.
|
||||
* @see https://fburl.com/42r9fxob
|
||||
*/
|
||||
- (void) webView:(WKWebView *)webView
|
||||
decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
|
||||
decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
|
||||
{
|
||||
static NSDictionary<NSNumber *, NSString *> *navigationTypes;
|
||||
static dispatch_once_t onceToken;
|
||||
|
||||
dispatch_once(&onceToken, ^{
|
||||
navigationTypes = @{
|
||||
@(WKNavigationTypeLinkActivated): @"click",
|
||||
@(WKNavigationTypeFormSubmitted): @"formsubmit",
|
||||
@(WKNavigationTypeBackForward): @"backforward",
|
||||
@(WKNavigationTypeReload): @"reload",
|
||||
@(WKNavigationTypeFormResubmitted): @"formresubmit",
|
||||
@(WKNavigationTypeOther): @"other",
|
||||
};
|
||||
});
|
||||
|
||||
WKNavigationType navigationType = navigationAction.navigationType;
|
||||
NSURLRequest *request = navigationAction.request;
|
||||
|
||||
if (_onShouldStartLoadWithRequest) {
|
||||
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
|
||||
[event addEntriesFromDictionary: @{
|
||||
@"url": (request.URL).absoluteString,
|
||||
@"navigationType": navigationTypes[@(navigationType)]
|
||||
}];
|
||||
if (![self.delegate webView:self
|
||||
shouldStartLoadForRequest:event
|
||||
withCallback:_onShouldStartLoadWithRequest]) {
|
||||
decisionHandler(WKNavigationResponsePolicyCancel);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (_onLoadingStart) {
|
||||
// We have this check to filter out iframe requests and whatnot
|
||||
BOOL isTopFrame = [request.URL isEqual:request.mainDocumentURL];
|
||||
if (isTopFrame) {
|
||||
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
|
||||
[event addEntriesFromDictionary: @{
|
||||
@"url": (request.URL).absoluteString,
|
||||
@"navigationType": navigationTypes[@(navigationType)]
|
||||
}];
|
||||
_onLoadingStart(event);
|
||||
}
|
||||
}
|
||||
|
||||
// Allow all navigation by default
|
||||
decisionHandler(WKNavigationResponsePolicyAllow);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when an error occurs while the web view is loading content.
|
||||
* @see https://fburl.com/km6vqenw
|
||||
*/
|
||||
- (void) webView:(WKWebView *)webView
|
||||
didFailProvisionalNavigation:(WKNavigation *)navigation
|
||||
withError:(NSError *)error
|
||||
{
|
||||
if (_onLoadingError) {
|
||||
if ([error.domain isEqualToString:NSURLErrorDomain] && error.code == NSURLErrorCancelled) {
|
||||
// NSURLErrorCancelled is reported when a page has a redirect OR if you load
|
||||
// a new URL in the WebView before the previous one came back. We can just
|
||||
// ignore these since they aren't real errors.
|
||||
// http://stackoverflow.com/questions/1024748/how-do-i-fix-nsurlerrordomain-error-999-in-iphone-3-0-os
|
||||
return;
|
||||
}
|
||||
|
||||
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
|
||||
[event addEntriesFromDictionary:@{
|
||||
@"didFailProvisionalNavigation": @YES,
|
||||
@"domain": error.domain,
|
||||
@"code": @(error.code),
|
||||
@"description": error.localizedDescription,
|
||||
}];
|
||||
_onLoadingError(event);
|
||||
}
|
||||
|
||||
[self setBackgroundColor: _savedBackgroundColor];
|
||||
}
|
||||
|
||||
- (void)evaluateJS:(NSString *)js
|
||||
thenCall: (void (^)(NSString*)) callback
|
||||
{
|
||||
[self.webView evaluateJavaScript: js completionHandler: ^(id result, NSError *error) {
|
||||
if (error == nil && callback != nil) {
|
||||
callback([NSString stringWithFormat:@"%@", result]);
|
||||
}
|
||||
}];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Called when the navigation is complete.
|
||||
* @see https://fburl.com/rtys6jlb
|
||||
*/
|
||||
- (void) webView:(WKWebView *)webView
|
||||
didFinishNavigation:(WKNavigation *)navigation
|
||||
{
|
||||
if (_messagingEnabled) {
|
||||
#if RCT_DEV
|
||||
|
||||
// Implementation inspired by Lodash.isNative.
|
||||
NSString *isPostMessageNative = @"String(String(window.postMessage) === String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage'))";
|
||||
[self evaluateJS: isPostMessageNative thenCall: ^(NSString *result) {
|
||||
if (! [result isEqualToString:@"true"]) {
|
||||
RCTLogError(@"Setting onMessage on a WebView overrides existing values of window.postMessage, but a previous value was defined");
|
||||
}
|
||||
}];
|
||||
#endif
|
||||
|
||||
NSString *source = [NSString stringWithFormat:
|
||||
@"(function() {"
|
||||
"window.originalPostMessage = window.postMessage;"
|
||||
|
||||
"window.postMessage = function(data) {"
|
||||
"window.webkit.messageHandlers.%@.postMessage(String(data));"
|
||||
"};"
|
||||
"})();",
|
||||
MessageHanderName
|
||||
];
|
||||
[self evaluateJS: source thenCall: nil];
|
||||
}
|
||||
|
||||
if (_injectedJavaScript) {
|
||||
[self evaluateJS: _injectedJavaScript thenCall: ^(NSString *jsEvaluationValue) {
|
||||
NSMutableDictionary *event = [self baseEvent];
|
||||
event[@"jsEvaluationValue"] = jsEvaluationValue;
|
||||
if (self.onLoadingFinish) {
|
||||
self.onLoadingFinish(event);
|
||||
}
|
||||
}];
|
||||
} else if (_onLoadingFinish) {
|
||||
_onLoadingFinish([self baseEvent]);
|
||||
}
|
||||
|
||||
[self setBackgroundColor: _savedBackgroundColor];
|
||||
}
|
||||
|
||||
- (void)injectJavaScript:(NSString *)script
|
||||
{
|
||||
[self evaluateJS: script thenCall: nil];
|
||||
}
|
||||
|
||||
- (void)goForward
|
||||
{
|
||||
[_webView goForward];
|
||||
}
|
||||
|
||||
- (void)goBack
|
||||
{
|
||||
[_webView goBack];
|
||||
}
|
||||
|
||||
- (void)reload
|
||||
{
|
||||
/**
|
||||
* When the initial load fails due to network connectivity issues,
|
||||
* [_webView reload] doesn't reload the webpage. Therefore, we must
|
||||
* manually call [_webView loadRequest:request].
|
||||
*/
|
||||
NSURLRequest *request = [RCTConvert NSURLRequest:self.source];
|
||||
if (request.URL && !_webView.URL.absoluteString.length) {
|
||||
[_webView loadRequest:request];
|
||||
}
|
||||
else {
|
||||
[_webView reload];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)stopLoading
|
||||
{
|
||||
[_webView stopLoading];
|
||||
}
|
||||
|
||||
- (void)setBounces:(BOOL)bounces
|
||||
{
|
||||
_bounces = bounces;
|
||||
_webView.scrollView.bounces = bounces;
|
||||
}
|
||||
@end
|
|
@ -0,0 +1,11 @@
|
|||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
#import <React/RCTViewManager.h>
|
||||
|
||||
@interface RCTWKWebViewManager : RCTViewManager
|
||||
@end
|
|
@ -1,15 +1,20 @@
|
|||
#import "RNCWebViewManager.h"
|
||||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
#import "RCTWKWebViewManager.h"
|
||||
|
||||
#import <React/RCTBridge.h>
|
||||
#import <React/RCTUIManager.h>
|
||||
#import <React/UIView+React.h>
|
||||
#import "RNCWebView.h"
|
||||
|
||||
@interface RNCWebViewManager () <RNCWebViewDelegate>
|
||||
#import <React/RCTDefines.h>
|
||||
#import "RCTWKWebView.h"
|
||||
|
||||
@interface RCTWKWebViewManager () <RCTWKWebViewDelegate>
|
||||
@end
|
||||
|
||||
@implementation RNCWebViewManager
|
||||
@implementation RCTWKWebViewManager
|
||||
{
|
||||
NSConditionLock *_shouldStartLoadLock;
|
||||
BOOL _shouldStartLoad;
|
||||
|
@ -19,35 +24,73 @@ RCT_EXPORT_MODULE()
|
|||
|
||||
- (UIView *)view
|
||||
{
|
||||
RNCWebView *webView = [RNCWebView new];
|
||||
RCTWKWebView *webView = [RCTWKWebView new];
|
||||
webView.delegate = self;
|
||||
return webView;
|
||||
}
|
||||
|
||||
RCT_EXPORT_VIEW_PROPERTY(source, NSDictionary)
|
||||
RCT_REMAP_VIEW_PROPERTY(bounces, _webView.scrollView.bounces, BOOL)
|
||||
RCT_REMAP_VIEW_PROPERTY(scrollEnabled, _webView.scrollView.scrollEnabled, BOOL)
|
||||
RCT_REMAP_VIEW_PROPERTY(decelerationRate, _webView.scrollView.decelerationRate, CGFloat)
|
||||
RCT_EXPORT_VIEW_PROPERTY(scalesPageToFit, BOOL)
|
||||
RCT_EXPORT_VIEW_PROPERTY(messagingEnabled, BOOL)
|
||||
RCT_EXPORT_VIEW_PROPERTY(injectedJavaScript, NSString)
|
||||
RCT_EXPORT_VIEW_PROPERTY(contentInset, UIEdgeInsets)
|
||||
RCT_EXPORT_VIEW_PROPERTY(automaticallyAdjustContentInsets, BOOL)
|
||||
RCT_EXPORT_VIEW_PROPERTY(onLoadingStart, RCTDirectEventBlock)
|
||||
RCT_EXPORT_VIEW_PROPERTY(onLoadingFinish, RCTDirectEventBlock)
|
||||
RCT_EXPORT_VIEW_PROPERTY(onLoadingError, RCTDirectEventBlock)
|
||||
RCT_EXPORT_VIEW_PROPERTY(onMessage, RCTDirectEventBlock)
|
||||
RCT_EXPORT_VIEW_PROPERTY(onShouldStartLoadWithRequest, RCTDirectEventBlock)
|
||||
RCT_REMAP_VIEW_PROPERTY(allowsInlineMediaPlayback, _webView.allowsInlineMediaPlayback, BOOL)
|
||||
RCT_REMAP_VIEW_PROPERTY(mediaPlaybackRequiresUserAction, _webView.mediaPlaybackRequiresUserAction, BOOL)
|
||||
RCT_REMAP_VIEW_PROPERTY(dataDetectorTypes, _webView.dataDetectorTypes, UIDataDetectorTypes)
|
||||
RCT_EXPORT_VIEW_PROPERTY(injectedJavaScript, NSString)
|
||||
RCT_EXPORT_VIEW_PROPERTY(allowsInlineMediaPlayback, BOOL)
|
||||
RCT_EXPORT_VIEW_PROPERTY(mediaPlaybackRequiresUserAction, BOOL)
|
||||
#if WEBKIT_IOS_10_APIS_AVAILABLE
|
||||
RCT_EXPORT_VIEW_PROPERTY(dataDetectorTypes, WKDataDetectorTypes)
|
||||
#endif
|
||||
RCT_EXPORT_VIEW_PROPERTY(contentInset, UIEdgeInsets)
|
||||
RCT_EXPORT_VIEW_PROPERTY(automaticallyAdjustContentInsets, BOOL)
|
||||
|
||||
/**
|
||||
* Expose methods to enable messaging the webview.
|
||||
*/
|
||||
RCT_EXPORT_VIEW_PROPERTY(messagingEnabled, BOOL)
|
||||
RCT_EXPORT_VIEW_PROPERTY(onMessage, RCTDirectEventBlock)
|
||||
|
||||
RCT_EXPORT_METHOD(postMessage:(nonnull NSNumber *)reactTag message:(NSString *)message)
|
||||
{
|
||||
[self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, RCTWKWebView *> *viewRegistry) {
|
||||
RCTWKWebView *view = viewRegistry[reactTag];
|
||||
if (![view isKindOfClass:[RCTWKWebView class]]) {
|
||||
RCTLogError(@"Invalid view returned from registry, expecting RCTWebView, got: %@", view);
|
||||
} else {
|
||||
[view postMessage:message];
|
||||
}
|
||||
}];
|
||||
}
|
||||
|
||||
RCT_CUSTOM_VIEW_PROPERTY(bounces, BOOL, RCTWKWebView) {
|
||||
view.bounces = json == nil ? true : [RCTConvert BOOL: json];
|
||||
}
|
||||
|
||||
RCT_CUSTOM_VIEW_PROPERTY(scrollEnabled, BOOL, RCTWKWebView) {
|
||||
view.scrollEnabled = json == nil ? true : [RCTConvert BOOL: json];
|
||||
}
|
||||
|
||||
RCT_CUSTOM_VIEW_PROPERTY(decelerationRate, CGFloat, RCTWKWebView) {
|
||||
view.decelerationRate = json == nil ? UIScrollViewDecelerationRateNormal : [RCTConvert CGFloat: json];
|
||||
}
|
||||
|
||||
RCT_EXPORT_METHOD(injectJavaScript:(nonnull NSNumber *)reactTag script:(NSString *)script)
|
||||
{
|
||||
[self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, RCTWKWebView *> *viewRegistry) {
|
||||
RCTWKWebView *view = viewRegistry[reactTag];
|
||||
if (![view isKindOfClass:[RCTWKWebView class]]) {
|
||||
RCTLogError(@"Invalid view returned from registry, expecting RCTWebView, got: %@", view);
|
||||
} else {
|
||||
[view injectJavaScript:script];
|
||||
}
|
||||
}];
|
||||
}
|
||||
|
||||
RCT_EXPORT_METHOD(goBack:(nonnull NSNumber *)reactTag)
|
||||
{
|
||||
[self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, RNCWebView *> *viewRegistry) {
|
||||
RNCWebView *view = viewRegistry[reactTag];
|
||||
if (![view isKindOfClass:[RNCWebView class]]) {
|
||||
RCTLogError(@"Invalid view returned from registry, expecting RNCWebView, got: %@", view);
|
||||
[self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, RCTWKWebView *> *viewRegistry) {
|
||||
RCTWKWebView *view = viewRegistry[reactTag];
|
||||
if (![view isKindOfClass:[RCTWKWebView class]]) {
|
||||
RCTLogError(@"Invalid view returned from registry, expecting RCTWebView, got: %@", view);
|
||||
} else {
|
||||
[view goBack];
|
||||
}
|
||||
|
@ -56,10 +99,10 @@ RCT_EXPORT_METHOD(goBack:(nonnull NSNumber *)reactTag)
|
|||
|
||||
RCT_EXPORT_METHOD(goForward:(nonnull NSNumber *)reactTag)
|
||||
{
|
||||
[self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
|
||||
id view = viewRegistry[reactTag];
|
||||
if (![view isKindOfClass:[RNCWebView class]]) {
|
||||
RCTLogError(@"Invalid view returned from registry, expecting RNCWebView, got: %@", view);
|
||||
[self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, RCTWKWebView *> *viewRegistry) {
|
||||
RCTWKWebView *view = viewRegistry[reactTag];
|
||||
if (![view isKindOfClass:[RCTWKWebView class]]) {
|
||||
RCTLogError(@"Invalid view returned from registry, expecting RCTWebView, got: %@", view);
|
||||
} else {
|
||||
[view goForward];
|
||||
}
|
||||
|
@ -68,10 +111,10 @@ RCT_EXPORT_METHOD(goForward:(nonnull NSNumber *)reactTag)
|
|||
|
||||
RCT_EXPORT_METHOD(reload:(nonnull NSNumber *)reactTag)
|
||||
{
|
||||
[self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, RNCWebView *> *viewRegistry) {
|
||||
RNCWebView *view = viewRegistry[reactTag];
|
||||
if (![view isKindOfClass:[RNCWebView class]]) {
|
||||
RCTLogError(@"Invalid view returned from registry, expecting RNCWebView, got: %@", view);
|
||||
[self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, RCTWKWebView *> *viewRegistry) {
|
||||
RCTWKWebView *view = viewRegistry[reactTag];
|
||||
if (![view isKindOfClass:[RCTWKWebView class]]) {
|
||||
RCTLogError(@"Invalid view returned from registry, expecting RCTWebView, got: %@", view);
|
||||
} else {
|
||||
[view reload];
|
||||
}
|
||||
|
@ -80,45 +123,21 @@ RCT_EXPORT_METHOD(reload:(nonnull NSNumber *)reactTag)
|
|||
|
||||
RCT_EXPORT_METHOD(stopLoading:(nonnull NSNumber *)reactTag)
|
||||
{
|
||||
[self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, RNCWebView *> *viewRegistry) {
|
||||
RNCWebView *view = viewRegistry[reactTag];
|
||||
if (![view isKindOfClass:[RNCWebView class]]) {
|
||||
RCTLogError(@"Invalid view returned from registry, expecting RNCWebView, got: %@", view);
|
||||
[self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, RCTWKWebView *> *viewRegistry) {
|
||||
RCTWKWebView *view = viewRegistry[reactTag];
|
||||
if (![view isKindOfClass:[RCTWKWebView class]]) {
|
||||
RCTLogError(@"Invalid view returned from registry, expecting RCTWebView, got: %@", view);
|
||||
} else {
|
||||
[view stopLoading];
|
||||
}
|
||||
}];
|
||||
}
|
||||
|
||||
RCT_EXPORT_METHOD(postMessage:(nonnull NSNumber *)reactTag message:(NSString *)message)
|
||||
{
|
||||
[self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, RNCWebView *> *viewRegistry) {
|
||||
RNCWebView *view = viewRegistry[reactTag];
|
||||
if (![view isKindOfClass:[RNCWebView class]]) {
|
||||
RCTLogError(@"Invalid view returned from registry, expecting RNCWebView, got: %@", view);
|
||||
} else {
|
||||
[view postMessage:message];
|
||||
}
|
||||
}];
|
||||
}
|
||||
|
||||
RCT_EXPORT_METHOD(injectJavaScript:(nonnull NSNumber *)reactTag script:(NSString *)script)
|
||||
{
|
||||
[self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, RNCWebView *> *viewRegistry) {
|
||||
RNCWebView *view = viewRegistry[reactTag];
|
||||
if (![view isKindOfClass:[RNCWebView class]]) {
|
||||
RCTLogError(@"Invalid view returned from registry, expecting RNCWebView, got: %@", view);
|
||||
} else {
|
||||
[view injectJavaScript:script];
|
||||
}
|
||||
}];
|
||||
}
|
||||
|
||||
#pragma mark - Exported synchronous methods
|
||||
|
||||
- (BOOL)webView:(__unused RNCWebView *)webView
|
||||
- (BOOL) webView:(RCTWKWebView *)webView
|
||||
shouldStartLoadForRequest:(NSMutableDictionary<NSString *, id> *)request
|
||||
withCallback:(RCTDirectEventBlock)callback
|
||||
withCallback:(RCTDirectEventBlock)callback
|
||||
{
|
||||
_shouldStartLoadLock = [[NSConditionLock alloc] initWithCondition:arc4random()];
|
||||
_shouldStartLoad = YES;
|
|
@ -1,39 +0,0 @@
|
|||
#import <React/RCTView.h>
|
||||
|
||||
@class RNCWebView;
|
||||
|
||||
/**
|
||||
* Special scheme used to pass messages to the injectedJavaScript
|
||||
* code without triggering a page load. Usage:
|
||||
*
|
||||
* window.location.href = RNCJSNavigationScheme + '://hello'
|
||||
*/
|
||||
extern NSString *const RNCJSNavigationScheme;
|
||||
|
||||
@protocol RNCWebViewDelegate <NSObject>
|
||||
|
||||
- (BOOL)webView:(RNCWebView *)webView
|
||||
shouldStartLoadForRequest:(NSMutableDictionary<NSString *, id> *)request
|
||||
withCallback:(RCTDirectEventBlock)callback;
|
||||
|
||||
@end
|
||||
|
||||
@interface RNCWebView : RCTView
|
||||
|
||||
@property (nonatomic, weak) id<RNCWebViewDelegate> delegate;
|
||||
|
||||
@property (nonatomic, copy) NSDictionary *source;
|
||||
@property (nonatomic, assign) UIEdgeInsets contentInset;
|
||||
@property (nonatomic, assign) BOOL automaticallyAdjustContentInsets;
|
||||
@property (nonatomic, assign) BOOL messagingEnabled;
|
||||
@property (nonatomic, copy) NSString *injectedJavaScript;
|
||||
@property (nonatomic, assign) BOOL scalesPageToFit;
|
||||
|
||||
- (void)goForward;
|
||||
- (void)goBack;
|
||||
- (void)reload;
|
||||
- (void)stopLoading;
|
||||
- (void)postMessage:(NSString *)message;
|
||||
- (void)injectJavaScript:(NSString *)script;
|
||||
|
||||
@end
|
343
ios/RNCWebView.m
343
ios/RNCWebView.m
|
@ -1,343 +0,0 @@
|
|||
#import "RNCWebView.h"
|
||||
|
||||
// #import <UIKit/UIKit.h>
|
||||
#import <React/RCTAutoInsetsProtocol.h>
|
||||
#import <React/RCTConvert.h>
|
||||
#import <React/RCTEventDispatcher.h>
|
||||
#import <React/RCTLog.h>
|
||||
#import <React/RCTUtils.h>
|
||||
#import <React/RCTView.h>
|
||||
#import <React/UIView+React.h>
|
||||
|
||||
NSString *const RNCJSNavigationScheme = @"react-js-navigation";
|
||||
|
||||
static NSString *const kPostMessageHost = @"postMessage";
|
||||
|
||||
@interface RNCWebView () <UIWebViewDelegate, RCTAutoInsetsProtocol>
|
||||
|
||||
@property (nonatomic, copy) RCTDirectEventBlock onLoadingStart;
|
||||
@property (nonatomic, copy) RCTDirectEventBlock onLoadingFinish;
|
||||
@property (nonatomic, copy) RCTDirectEventBlock onLoadingError;
|
||||
@property (nonatomic, copy) RCTDirectEventBlock onShouldStartLoadWithRequest;
|
||||
@property (nonatomic, copy) RCTDirectEventBlock onMessage;
|
||||
|
||||
@end
|
||||
|
||||
@implementation RNCWebView
|
||||
{
|
||||
UIWebView *_webView;
|
||||
NSString *_injectedJavaScript;
|
||||
}
|
||||
|
||||
- (void)dealloc
|
||||
{
|
||||
_webView.delegate = nil;
|
||||
}
|
||||
|
||||
- (instancetype)initWithFrame:(CGRect)frame
|
||||
{
|
||||
if ((self = [super initWithFrame:frame])) {
|
||||
super.backgroundColor = [UIColor clearColor];
|
||||
_automaticallyAdjustContentInsets = YES;
|
||||
_contentInset = UIEdgeInsetsZero;
|
||||
_webView = [[UIWebView alloc] initWithFrame:self.bounds];
|
||||
_webView.delegate = self;
|
||||
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
|
||||
if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
|
||||
_webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
|
||||
}
|
||||
#endif
|
||||
[self addSubview:_webView];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder)
|
||||
|
||||
- (void)goForward
|
||||
{
|
||||
[_webView goForward];
|
||||
}
|
||||
|
||||
- (void)goBack
|
||||
{
|
||||
[_webView goBack];
|
||||
}
|
||||
|
||||
- (void)reload
|
||||
{
|
||||
NSURLRequest *request = [RCTConvert NSURLRequest:self.source];
|
||||
if (request.URL && !_webView.request.URL.absoluteString.length) {
|
||||
[_webView loadRequest:request];
|
||||
}
|
||||
else {
|
||||
[_webView reload];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)stopLoading
|
||||
{
|
||||
[_webView stopLoading];
|
||||
}
|
||||
|
||||
- (void)postMessage:(NSString *)message
|
||||
{
|
||||
NSDictionary *eventInitDict = @{
|
||||
@"data": message,
|
||||
};
|
||||
NSString *source = [NSString
|
||||
stringWithFormat:@"document.dispatchEvent(new MessageEvent('message', %@));",
|
||||
RCTJSONStringify(eventInitDict, NULL)
|
||||
];
|
||||
[_webView stringByEvaluatingJavaScriptFromString:source];
|
||||
}
|
||||
|
||||
- (void)injectJavaScript:(NSString *)script
|
||||
{
|
||||
[_webView stringByEvaluatingJavaScriptFromString:script];
|
||||
}
|
||||
|
||||
- (void)setSource:(NSDictionary *)source
|
||||
{
|
||||
if (![_source isEqualToDictionary:source]) {
|
||||
_source = [source copy];
|
||||
|
||||
// Check for a static html source first
|
||||
NSString *html = [RCTConvert NSString:source[@"html"]];
|
||||
if (html) {
|
||||
NSURL *baseURL = [RCTConvert NSURL:source[@"baseUrl"]];
|
||||
if (!baseURL) {
|
||||
baseURL = [NSURL URLWithString:@"about:blank"];
|
||||
}
|
||||
[_webView loadHTMLString:html baseURL:baseURL];
|
||||
return;
|
||||
}
|
||||
|
||||
NSURLRequest *request = [RCTConvert NSURLRequest:source];
|
||||
// Because of the way React works, as pages redirect, we actually end up
|
||||
// passing the redirect urls back here, so we ignore them if trying to load
|
||||
// the same url. We'll expose a call to 'reload' to allow a user to load
|
||||
// the existing page.
|
||||
if ([request.URL isEqual:_webView.request.URL]) {
|
||||
return;
|
||||
}
|
||||
if (!request.URL) {
|
||||
// Clear the webview
|
||||
[_webView loadHTMLString:@"" baseURL:nil];
|
||||
return;
|
||||
}
|
||||
[_webView loadRequest:request];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)layoutSubviews
|
||||
{
|
||||
[super layoutSubviews];
|
||||
_webView.frame = self.bounds;
|
||||
}
|
||||
|
||||
- (void)setContentInset:(UIEdgeInsets)contentInset
|
||||
{
|
||||
_contentInset = contentInset;
|
||||
[RCTView autoAdjustInsetsForView:self
|
||||
withScrollView:_webView.scrollView
|
||||
updateOffset:NO];
|
||||
}
|
||||
|
||||
- (void)setScalesPageToFit:(BOOL)scalesPageToFit
|
||||
{
|
||||
if (_webView.scalesPageToFit != scalesPageToFit) {
|
||||
_webView.scalesPageToFit = scalesPageToFit;
|
||||
[_webView reload];
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)scalesPageToFit
|
||||
{
|
||||
return _webView.scalesPageToFit;
|
||||
}
|
||||
|
||||
- (void)setBackgroundColor:(UIColor *)backgroundColor
|
||||
{
|
||||
CGFloat alpha = CGColorGetAlpha(backgroundColor.CGColor);
|
||||
self.opaque = _webView.opaque = (alpha == 1.0);
|
||||
_webView.backgroundColor = backgroundColor;
|
||||
}
|
||||
|
||||
- (UIColor *)backgroundColor
|
||||
{
|
||||
return _webView.backgroundColor;
|
||||
}
|
||||
|
||||
- (NSMutableDictionary<NSString *, id> *)baseEvent
|
||||
{
|
||||
NSMutableDictionary<NSString *, id> *event = [[NSMutableDictionary alloc] initWithDictionary:@{
|
||||
@"url": _webView.request.URL.absoluteString ?: @"",
|
||||
@"loading" : @(_webView.loading),
|
||||
@"title": [_webView stringByEvaluatingJavaScriptFromString:@"document.title"],
|
||||
@"canGoBack": @(_webView.canGoBack),
|
||||
@"canGoForward" : @(_webView.canGoForward),
|
||||
}];
|
||||
|
||||
return event;
|
||||
}
|
||||
|
||||
- (void)refreshContentInset
|
||||
{
|
||||
[RCTView autoAdjustInsetsForView:self
|
||||
withScrollView:_webView.scrollView
|
||||
updateOffset:YES];
|
||||
}
|
||||
|
||||
#pragma mark - UIWebViewDelegate methods
|
||||
|
||||
- (BOOL)webView:(__unused UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
|
||||
navigationType:(UIWebViewNavigationType)navigationType
|
||||
{
|
||||
BOOL isJSNavigation = [request.URL.scheme isEqualToString:RNCJSNavigationScheme];
|
||||
|
||||
static NSDictionary<NSNumber *, NSString *> *navigationTypes;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
navigationTypes = @{
|
||||
@(UIWebViewNavigationTypeLinkClicked): @"click",
|
||||
@(UIWebViewNavigationTypeFormSubmitted): @"formsubmit",
|
||||
@(UIWebViewNavigationTypeBackForward): @"backforward",
|
||||
@(UIWebViewNavigationTypeReload): @"reload",
|
||||
@(UIWebViewNavigationTypeFormResubmitted): @"formresubmit",
|
||||
@(UIWebViewNavigationTypeOther): @"other",
|
||||
};
|
||||
});
|
||||
|
||||
// skip this for the JS Navigation handler
|
||||
if (!isJSNavigation && _onShouldStartLoadWithRequest) {
|
||||
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
|
||||
[event addEntriesFromDictionary: @{
|
||||
@"url": (request.URL).absoluteString,
|
||||
@"navigationType": navigationTypes[@(navigationType)]
|
||||
}];
|
||||
if (![self.delegate webView:self
|
||||
shouldStartLoadForRequest:event
|
||||
withCallback:_onShouldStartLoadWithRequest]) {
|
||||
return NO;
|
||||
}
|
||||
}
|
||||
|
||||
if (_onLoadingStart) {
|
||||
// We have this check to filter out iframe requests and whatnot
|
||||
BOOL isTopFrame = [request.URL isEqual:request.mainDocumentURL];
|
||||
if (isTopFrame) {
|
||||
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
|
||||
[event addEntriesFromDictionary: @{
|
||||
@"url": (request.URL).absoluteString,
|
||||
@"navigationType": navigationTypes[@(navigationType)]
|
||||
}];
|
||||
_onLoadingStart(event);
|
||||
}
|
||||
}
|
||||
|
||||
if (isJSNavigation && [request.URL.host isEqualToString:kPostMessageHost]) {
|
||||
NSString *data = request.URL.query;
|
||||
data = [data stringByReplacingOccurrencesOfString:@"+" withString:@" "];
|
||||
data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
|
||||
|
||||
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
|
||||
[event addEntriesFromDictionary: @{
|
||||
@"data": data,
|
||||
}];
|
||||
|
||||
NSString *source = @"document.dispatchEvent(new MessageEvent('message:received'));";
|
||||
|
||||
[_webView stringByEvaluatingJavaScriptFromString:source];
|
||||
|
||||
_onMessage(event);
|
||||
}
|
||||
|
||||
// JS Navigation handler
|
||||
return !isJSNavigation;
|
||||
}
|
||||
|
||||
- (void)webView:(__unused UIWebView *)webView didFailLoadWithError:(NSError *)error
|
||||
{
|
||||
if (_onLoadingError) {
|
||||
if ([error.domain isEqualToString:NSURLErrorDomain] && error.code == NSURLErrorCancelled) {
|
||||
// NSURLErrorCancelled is reported when a page has a redirect OR if you load
|
||||
// a new URL in the WebView before the previous one came back. We can just
|
||||
// ignore these since they aren't real errors.
|
||||
// http://stackoverflow.com/questions/1024748/how-do-i-fix-nsurlerrordomain-error-999-in-iphone-3-0-os
|
||||
return;
|
||||
}
|
||||
|
||||
if ([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 102) {
|
||||
// Error code 102 "Frame load interrupted" is raised by the UIWebView if
|
||||
// its delegate returns FALSE from webView:shouldStartLoadWithRequest:navigationType
|
||||
// when the URL is from an http redirect. This is a common pattern when
|
||||
// implementing OAuth with a WebView.
|
||||
return;
|
||||
}
|
||||
|
||||
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
|
||||
[event addEntriesFromDictionary:@{
|
||||
@"domain": error.domain,
|
||||
@"code": @(error.code),
|
||||
@"description": error.localizedDescription,
|
||||
}];
|
||||
_onLoadingError(event);
|
||||
}
|
||||
}
|
||||
|
||||
- (void)webViewDidFinishLoad:(UIWebView *)webView
|
||||
{
|
||||
if (_messagingEnabled) {
|
||||
#if RCT_DEV
|
||||
// See isNative in lodash
|
||||
NSString *testPostMessageNative = @"String(window.postMessage) === String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage')";
|
||||
BOOL postMessageIsNative = [
|
||||
[webView stringByEvaluatingJavaScriptFromString:testPostMessageNative]
|
||||
isEqualToString:@"true"
|
||||
];
|
||||
if (!postMessageIsNative) {
|
||||
RCTLogError(@"Setting onMessage on a WebView overrides existing values of window.postMessage, but a previous value was defined");
|
||||
}
|
||||
#endif
|
||||
NSString *source = [NSString stringWithFormat:
|
||||
@"(function() {"
|
||||
"window.originalPostMessage = window.postMessage;"
|
||||
|
||||
"var messageQueue = [];"
|
||||
"var messagePending = false;"
|
||||
|
||||
"function processQueue() {"
|
||||
"if (!messageQueue.length || messagePending) return;"
|
||||
"messagePending = true;"
|
||||
"window.location = '%@://%@?' + encodeURIComponent(messageQueue.shift());"
|
||||
"}"
|
||||
|
||||
"window.postMessage = function(data) {"
|
||||
"messageQueue.push(String(data));"
|
||||
"processQueue();"
|
||||
"};"
|
||||
|
||||
"document.addEventListener('message:received', function(e) {"
|
||||
"messagePending = false;"
|
||||
"processQueue();"
|
||||
"});"
|
||||
"})();", RNCJSNavigationScheme, kPostMessageHost
|
||||
];
|
||||
[webView stringByEvaluatingJavaScriptFromString:source];
|
||||
}
|
||||
if (_injectedJavaScript != nil) {
|
||||
NSString *jsEvaluationValue = [webView stringByEvaluatingJavaScriptFromString:_injectedJavaScript];
|
||||
|
||||
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
|
||||
event[@"jsEvaluationValue"] = jsEvaluationValue;
|
||||
|
||||
_onLoadingFinish(event);
|
||||
}
|
||||
// we only need the final 'finishLoad' call so only fire the event when we're actually done loading.
|
||||
else if (_onLoadingFinish && !webView.loading && ![webView.request.URL.absoluteString isEqualToString:@"about:blank"]) {
|
||||
_onLoadingFinish([self baseEvent]);
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
|
@ -1,24 +0,0 @@
|
|||
|
||||
Pod::Spec.new do |s|
|
||||
s.name = "RNCWebView"
|
||||
s.version = "1.0.0"
|
||||
s.summary = "RNCWebView"
|
||||
s.description = <<-DESC
|
||||
RNCWebView
|
||||
DESC
|
||||
s.homepage = ""
|
||||
s.license = "MIT"
|
||||
# s.license = { :type => "MIT", :file => "FILE_LICENSE" }
|
||||
s.author = { "author" => "author@domain.cn" }
|
||||
s.platform = :ios, "7.0"
|
||||
s.source = { :git => "https://github.com/author/RNCWebView.git", :tag => "master" }
|
||||
s.source_files = "RNCWebView/**/*.{h,m}"
|
||||
s.requires_arc = true
|
||||
|
||||
|
||||
s.dependency "React"
|
||||
#s.dependency "others"
|
||||
|
||||
end
|
||||
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
#import <React/RCTViewManager.h>
|
||||
|
||||
@interface RNCWebViewManager : RCTViewManager
|
||||
|
||||
@end
|
|
@ -462,7 +462,7 @@ class WebView extends React.Component {
|
|||
this.updateNavigationState(event);
|
||||
};
|
||||
|
||||
onMessage = (event: Event) => {
|
||||
onMessage = (event) => {
|
||||
const { onMessage } = this.props;
|
||||
onMessage && onMessage(event);
|
||||
};
|
||||
|
|
|
@ -1,66 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
const React = require('react');
|
||||
const ReactNative = require('react-native');
|
||||
const { WebView } = ReactNative;
|
||||
|
||||
const { TestModule } = ReactNative.NativeModules;
|
||||
|
||||
class WebViewTest extends React.Component {
|
||||
render() {
|
||||
let firstMessageReceived = false;
|
||||
let secondMessageReceived = false;
|
||||
function processMessage(e) {
|
||||
const message = e.nativeEvent.data;
|
||||
if (message === 'First') {
|
||||
firstMessageReceived = true;
|
||||
}
|
||||
if (message === 'Second') {
|
||||
secondMessageReceived = true;
|
||||
}
|
||||
|
||||
// got both messages
|
||||
if (firstMessageReceived && secondMessageReceived) {
|
||||
TestModule.markTestPassed(true);
|
||||
}
|
||||
// wait for next message
|
||||
else if (firstMessageReceived && !secondMessageReceived) {
|
||||
return;
|
||||
}
|
||||
// first message got lost
|
||||
else if (!firstMessageReceived && secondMessageReceived) {
|
||||
throw new Error('First message got lost');
|
||||
}
|
||||
}
|
||||
const html =
|
||||
'Hello world' +
|
||||
'<script>' +
|
||||
"window.setTimeout(function(){window.postMessage('First'); window.postMessage('Second')}, 0)" +
|
||||
'</script>';
|
||||
|
||||
// fail if messages didn't get through;
|
||||
window.setTimeout(function () {
|
||||
throw new Error(
|
||||
firstMessageReceived
|
||||
? 'Both messages got lost'
|
||||
: 'Second message got lost',
|
||||
);
|
||||
}, 10000);
|
||||
|
||||
const source = {
|
||||
html: html,
|
||||
};
|
||||
|
||||
return (
|
||||
<WebView
|
||||
source={source}
|
||||
onMessage={processMessage}
|
||||
originWhitelist={['about:blank']}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
WebViewTest.displayName = 'WebViewTest';
|
||||
|
||||
module.exports = WebViewTest;
|
|
@ -727,7 +727,7 @@ class WebView extends React.Component {
|
|||
}
|
||||
}
|
||||
|
||||
_showRedboxOnPropChanges(prevProps, propName: string) {
|
||||
_showRedboxOnPropChanges(prevProps, propName) {
|
||||
if (this.props[propName] !== prevProps[propName]) {
|
||||
console.error(
|
||||
`Changes to property ${propName} do nothing after the initial render.`,
|
||||
|
|
|
@ -1,3 +1,13 @@
|
|||
/**
|
||||
* Copyright (c) 2015-present, Facebook, Inc.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*
|
||||
* @format
|
||||
* @flow
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
const escapeStringRegexp = require('escape-string-regexp');
|
||||
|
@ -13,4 +23,4 @@ const WebViewShared = {
|
|||
},
|
||||
};
|
||||
|
||||
export default WebViewShared;
|
||||
module.exports = WebViewShared;
|
||||
|
|
|
@ -1,51 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
const WebViewShared = require('WebViewShared');
|
||||
describe('WebViewShared', () => {
|
||||
it('extracts the origin correctly', () => {
|
||||
expect(WebViewShared.extractOrigin('http://facebook.com')).toBe(
|
||||
'http://facebook.com',
|
||||
);
|
||||
expect(WebViewShared.extractOrigin('https://facebook.com')).toBe(
|
||||
'https://facebook.com',
|
||||
);
|
||||
expect(WebViewShared.extractOrigin('http://facebook.com:8081')).toBe(
|
||||
'http://facebook.com:8081',
|
||||
);
|
||||
expect(WebViewShared.extractOrigin('ftp://facebook.com')).toBe(
|
||||
'ftp://facebook.com',
|
||||
);
|
||||
expect(WebViewShared.extractOrigin('myweirdscheme://')).toBe(
|
||||
'myweirdscheme://',
|
||||
);
|
||||
expect(WebViewShared.extractOrigin('http://facebook.com/')).toBe(
|
||||
'http://facebook.com',
|
||||
);
|
||||
expect(WebViewShared.extractOrigin('http://facebook.com/longerurl')).toBe(
|
||||
'http://facebook.com',
|
||||
);
|
||||
expect(
|
||||
WebViewShared.extractOrigin('http://facebook.com/http://facebook.com'),
|
||||
).toBe('http://facebook.com');
|
||||
expect(
|
||||
WebViewShared.extractOrigin('http://facebook.com//http://facebook.com'),
|
||||
).toBe('http://facebook.com');
|
||||
expect(
|
||||
WebViewShared.extractOrigin('http://facebook.com//http://facebook.com//'),
|
||||
).toBe('http://facebook.com');
|
||||
expect(WebViewShared.extractOrigin('about:blank')).toBe('about:blank');
|
||||
});
|
||||
|
||||
it('rejects bad urls', () => {
|
||||
expect(WebViewShared.extractOrigin('a/b')).toBeNull();
|
||||
expect(WebViewShared.extractOrigin('a//b')).toBeNull();
|
||||
});
|
||||
|
||||
it('creates a whitelist regex correctly', () => {
|
||||
expect(WebViewShared.originWhitelistToRegex('http://*')).toBe('http://.*');
|
||||
expect(WebViewShared.originWhitelistToRegex('*')).toBe('.*');
|
||||
expect(WebViewShared.originWhitelistToRegex('*//test')).toBe('.*//test');
|
||||
expect(WebViewShared.originWhitelistToRegex('*/*')).toBe('.*/.*');
|
||||
expect(WebViewShared.originWhitelistToRegex('*.com')).toBe('.*\\.com');
|
||||
});
|
||||
});
|
Loading…
Reference in New Issue