Permalink
Browse files

Add a injectJavaScript method to the WebView component

Summary:
Currently, < WebView > allows you to pass JS to execute within the view. This works great, but there currently is not a way to execute JS after the page is loaded. We needed this for our app.

We noticed that the WebView had messaging support added (see #9762) . Initially, this seemed like more than enough functionality for our use case - just write a function that's injected on initial load that accepts a message with JS, and `eval()` it. However, this broke once we realized that Content Security Policy can block the use of eval on pages. The native methods iOS provide to inject JS allow you to inject JS without CSP interfering. So, we just wrapped the native methods on iOS (and later Android) and it worked for our use case. The method injectJavaScript was born.

Now, after I wrote this code, I realized that #8798 exists and hadn't been merged because of a lack of tests. I commend what was done in #8798 as it sorely solves a problem (injecting JS after the initial load) and has more features than what I'
Closes #11358

Differential Revision: D4390425

fbshipit-source-id: 02813127f8cf60fd84229cb26eeea7f8922d03b3
  • Loading branch information...
lukemiles authored and facebook-github-bot committed Jan 7, 2017
1 parent 3d1bdcc commit da9a712a9e17942dcd05b8d955f0764c2026a4ad
@@ -264,6 +264,35 @@ class MessagingTest extends React.Component {
}
}
class InjectJS extends React.Component {
webview = null;
injectJS = () => {
const script = 'document.write("Injected JS ")'; // eslint-disable-line quotes
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,
@@ -442,5 +471,9 @@ exports.examples = [
{
title: 'Mesaging Test',
render(): ReactElement<any> { return <MessagingTest />; }
}
},
{
title: 'Inject JavaScript',
render(): React.Element<any> { return <InjectJS />; }
},
];
@@ -286,6 +286,20 @@ class WebView extends React.Component {
);
};
/**
* Injects a javascript string into the referenced WebView. Deliberately does not
* return a response because using eval() to return a response breaks this method
* on pages with a Content Security Policy that disallows eval(). If you need that
* functionality, look into postMessage/onMessage.
*/
injectJavaScript = (data) => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
UIManager.RCTWebView.Commands.injectJavaScript,
[data]
);
};
/**
* We return an event with a bunch of fields including:
* url, title, loading, canGoBack, canGoForward
@@ -489,6 +489,20 @@ class WebView extends React.Component {
);
};
/**
* Injects a javascript string into the referenced WebView. Deliberately does not
* return a response because using eval() to return a response breaks this method
* on pages with a Content Security Policy that disallows eval(). If you need that
* functionality, look into postMessage/onMessage.
*/
injectJavaScript = (data) => {
UIManager.dispatchViewManagerCommand(
this.getWebViewHandle(),
UIManager.RCTWebView.Commands.injectJavaScript,
[data]
);
};
/**
* We return an event with a bunch of fields including:
* url, title, loading, canGoBack, canGoForward
View
@@ -43,5 +43,6 @@ shouldStartLoadForRequest:(NSMutableDictionary<NSString *, id> *)request
- (void)reload;
- (void)stopLoading;
- (void)postMessage:(NSString *)message;
- (void)injectJavaScript:(NSString *)script;
@end
View
@@ -96,6 +96,11 @@ - (void)postMessage:(NSString *)message
[_webView stringByEvaluatingJavaScriptFromString:source];
}
- (void)injectJavaScript:(NSString *)script
{
[_webView stringByEvaluatingJavaScriptFromString:script];
}
- (void)setSource:(NSDictionary *)source
{
if (![_source isEqualToDictionary:source]) {
@@ -111,6 +111,18 @@ - (UIView *)view
}];
}
RCT_EXPORT_METHOD(injectJavaScript:(nonnull NSNumber *)reactTag script:(NSString *)script)
{
[self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, RCTWebView *> *viewRegistry) {
RCTWebView *view = viewRegistry[reactTag];
if (![view isKindOfClass:[RCTWebView class]]) {
RCTLogError(@"Invalid view returned from registry, expecting RCTWebView, got: %@", view);
} else {
[view injectJavaScript:script];
}
}];
}
#pragma mark - Exported synchronous methods
- (BOOL)webView:(__unused RCTWebView *)webView
@@ -95,6 +95,7 @@
public static final int COMMAND_RELOAD = 3;
public static final int COMMAND_STOP_LOADING = 4;
public static final int COMMAND_POST_MESSAGE = 5;
public static final int COMMAND_INJECT_JAVASCRIPT = 6;
// Use `webView.loadUrl("about:blank")` to reliably reset the view
// state and release page resources (including any running JavaScript).
@@ -477,7 +478,9 @@ protected void addEventEmitters(ThemedReactContext reactContext, WebView view) {
"goForward", COMMAND_GO_FORWARD,
"reload", COMMAND_RELOAD,
"stopLoading", COMMAND_STOP_LOADING,
"postMessage", COMMAND_POST_MESSAGE);
"postMessage", COMMAND_POST_MESSAGE,
"injectJavaScript", COMMAND_INJECT_JAVASCRIPT
);
}
@Override
@@ -504,6 +507,9 @@ public void receiveCommand(WebView root, int commandId, @Nullable ReadableArray
throw new RuntimeException(e);
}
break;
case COMMAND_INJECT_JAVASCRIPT:
root.loadUrl("javascript:" + args.getString(0));
break;
}
}

2 comments on commit da9a712

@faceach

This comment has been minimized.

Show comment
Hide comment
@faceach

faceach Mar 3, 2017

Good job! This is what I need. 👍

faceach replied Mar 3, 2017

Good job! This is what I need. 👍

@cvillecsteele

This comment has been minimized.

Show comment
Hide comment
@cvillecsteele

cvillecsteele replied Mar 9, 2017

+1

Please sign in to comment.