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)

Most upvoted comments

window.postMessage({message: 'hello!'}) throws Not enough arguments

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:

window.webkit.messageHandlers.reactNative.postMessage(data);

… Indeed, this alias method shouldn’t need a target origin; looks like you’re using window.postMessage() (the actual ECMAScript window.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 *)navigation callback in ios/RCTWKWebView/RCTWKWebView.m. So the whole webpage will need to be loaded before the window.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 injectJavaScript prop:

window.originalPostMessage = window.postMessage;
window.postMessage = function() {
    return window.webkit.messageHandlers.reactNative.postMessage.apply(window.webkit.messageHandlers.reactNative, arguments);
};

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.postMessage method!

Yes. This is added to be “compatible” with <WebView>. I don’t like it either. But it helps people migrating from WebView.