WebView inject javascript before window.onload
See original GitHub issueDescription
When using the WebView API to communicate over postMessage and inject Javascript using the injectedJavaScript prop, the webpage has to wait until window.onload.
In the example, if you run window.postMessage('"Hello" from the web view'); without waiting for the button click, you will see an exception because React Native hasn’t injected postMessage yet.
Solution
Not sure about the specifics, but ideally the React Native injected code would run before the document javascript runs.
Additional Information
react-native-cli: 2.0.1 react-native: 0.43.2 ProductName: Mac OS X ProductVersion: 10.12.3 BuildVersion: 16D32 Xcode 8.3 Build version 8E162
Issue Analytics
- State:
- Created 6 years ago
- Reactions:5
- Comments:6 (3 by maintainers)
Top Results From Across the Web
Android WebView Inject Javascript before html loaded
I had the same problem and I solved it. I hide WebView before load and show after page loaded. webView.getSettings().setJavaScriptEnabled(true); b.webView.
Read more >Inject javascript before the page is loaded - Google Groups
There isn't a particularly good way to inject JS into every page with WebView, especially if the page content is third-party and can't...
Read more >Inject JS into Android's WebView - Medium
Inject JS into Android's WebView. WebView gives developers an easy way to embed a web-based application to an Android app with almost no...
Read more >Inject JavaScript into WKWebView - Apps Developer Blog
In Swift, it is possible to inject a JavaScript code into a WKWebView and execute it from your app. The below code example...
Read more >JavaScript Manipulation on iOS Using WebKit | Capital One
let scriptSource = "window.webkit.messageHandlers.test.postMessage(`Hello, world!`);" // Instantiate a WKUserScript object and specify when you'd like to inject ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

As React Native use UIWebView, I think you can’t inject JavaScript before WebView loading finished.
But in WKWebView, you can inject JavaScript at document start via API:
- (instancetype)initWithSource:(NSString *)source injectionTime:(WKUserScriptInjectionTime)injectionTime forMainFrameOnly:(BOOL)forMainFrameOnly;- (void)addUserScript:(WKUserScript *)userScript;Experiencing the same problem. RN:
html js:
It won’t work.
So, I use this workaround:
Another issue talking about this: https://github.com/facebook/react-native/issues/11594