mirror of
https://github.com/zhigang1992/react-native.git
synced 2026-04-23 03:50:11 +08:00
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
This commit is contained in:
committed by
Facebook Github Bot
parent
3d1bdcc2e3
commit
da9a712a9e
@@ -95,6 +95,7 @@ public class ReactWebViewManager extends SimpleViewManager<WebView> {
|
||||
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 @@ public class ReactWebViewManager extends SimpleViewManager<WebView> {
|
||||
"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 class ReactWebViewManager extends SimpleViewManager<WebView> {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
break;
|
||||
case COMMAND_INJECT_JAVASCRIPT:
|
||||
root.loadUrl("javascript:" + args.getString(0));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user