From da9a712a9e17942dcd05b8d955f0764c2026a4ad Mon Sep 17 00:00:00 2001 From: Luke Miles Date: Fri, 6 Jan 2017 20:13:20 -0800 Subject: [PATCH] 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 https://github.com/facebook/react-native/pull/11358 Differential Revision: D4390425 fbshipit-source-id: 02813127f8cf60fd84229cb26eeea7f8922d03b3 --- Examples/UIExplorer/js/WebViewExample.js | 35 ++++++++++++++++++- .../Components/WebView/WebView.android.js | 14 ++++++++ Libraries/Components/WebView/WebView.ios.js | 14 ++++++++ React/Views/RCTWebView.h | 1 + React/Views/RCTWebView.m | 5 +++ React/Views/RCTWebViewManager.m | 12 +++++++ .../views/webview/ReactWebViewManager.java | 8 ++++- 7 files changed, 87 insertions(+), 2 deletions(-) diff --git a/Examples/UIExplorer/js/WebViewExample.js b/Examples/UIExplorer/js/WebViewExample.js index be1fb44ae..a0f3c6357 100644 --- a/Examples/UIExplorer/js/WebViewExample.js +++ b/Examples/UIExplorer/js/WebViewExample.js @@ -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 ( + + { this.webview = webview; }} + style={{ + backgroundColor: BGWASH, + height: 300, + }} + source={{uri: 'https://www.facebook.com'}} + scalesPageToFit={true} + /> + +