react-native-wkwebview: window.postMessage is not ready right away because of WKUserScriptInjectionTime atDocumentEnd
Version: 1.21 (iOS: 11.4)
window.webkit.messageHandlers.reactNative.postMessage works as documented, but window.postMessage({message: 'hello!'}) throws Not enough arguments
When I try window.postMessage({message: 'hello!'}, '*'), the message is not being sent to RN.
Thanks!
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Comments: 16 (3 by maintainers)
Indeed, it is required to specify the target origin: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
In this library,
window.postMessage(data)is an alias for:… Indeed, this alias method shouldn’t need a target origin; looks like you’re using
window.postMessage()(the actual ECMAScriptwindow.postMessage()method) before the alias has been set, which may be why it complains about requiring an origin argument.The alias is only set upon the
- (void)webView:(WKWebView *)webView didFinishNavigation:(__unused WKNavigation *)navigationcallback inios/RCTWKWebView/RCTWKWebView.m. So the whole webpage will need to be loaded before thewindow.postMessage(data)alias is available.As a quick guess, you could try running the same aliasing code in an earlier part of the webpage loading lifecycle – in the new
injectJavaScriptprop:Disclaimer: there may well be a valid reason for this aliasing happening only after the page has been loaded; I haven’t read the code in detail.
You could consider submitting a PR that moves the aliasing code to that earlier part of the webpage loading lifecycle if you could convincingly determine that there are no issues in doing so.
… Otherwise, just use the non-aliased
window.webkit.messageHandlers.reactNative.postMessagemethod!Yes. This is added to be “compatible” with <WebView>. I don’t like it either. But it helps people migrating from WebView.