diff --git a/android/src/main/java/com/reactnativecommunity/webview/RNCWebView.java b/android/src/main/java/com/reactnativecommunity/webview/RNCWebView.java index c80cf753f..efa843b07 100644 --- a/android/src/main/java/com/reactnativecommunity/webview/RNCWebView.java +++ b/android/src/main/java/com/reactnativecommunity/webview/RNCWebView.java @@ -79,6 +79,7 @@ public class RNCWebView extends WebView implements LifecycleEventListener { protected boolean nestedScrollEnabled = false; protected ProgressChangedFilter progressChangedFilter; protected boolean mActive = true; + protected @Nullable String mLastCommittedUrl; /** * WebView must be created with an context of the current activity @@ -256,6 +257,14 @@ public boolean getMessagingEnabled() { return this.messagingEnabled; } + public void setLastCommittedUrl(@Nullable String url) { + this.mLastCommittedUrl = url; + } + + public @Nullable String getLastCommittedUrl() { + return this.mLastCommittedUrl; + } + @SuppressLint("RestrictedApi") protected void createRNCWebViewBridge(RNCWebView webView) { if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)){ @@ -485,8 +494,11 @@ protected class RNCWebViewBridge { @JavascriptInterface public void postMessage(String message) { if (mWebView.getMessagingEnabled()) { + // Capture top frame URL eagerly to avoid race condition if a navigation + // occurs between now and when the runnable executes on the main thread. + String topFrameUrl = mWebView.getLastCommittedUrl(); // Post to main thread because `mWebView.getUrl()` requires to be executed on main. - mWebView.post(() -> mWebView.onMessage(message, mWebView.getUrl(), null, mWebView.getUrl())); + mWebView.post(() -> mWebView.onMessage(message, mWebView.getUrl(), null, topFrameUrl)); } else { FLog.w(TAG, "ReactNativeWebView.postMessage method was called but messaging is disabled. Pass an onMessage handler to the WebView."); } diff --git a/android/src/main/java/com/reactnativecommunity/webview/RNCWebViewClient.java b/android/src/main/java/com/reactnativecommunity/webview/RNCWebViewClient.java index 0287e1c56..ac33d3898 100644 --- a/android/src/main/java/com/reactnativecommunity/webview/RNCWebViewClient.java +++ b/android/src/main/java/com/reactnativecommunity/webview/RNCWebViewClient.java @@ -87,6 +87,7 @@ public void onPageStarted(WebView webView, String url, Bitmap favicon) { mLastLoadFailed = false; RNCWebView reactWebView = (RNCWebView) webView; + reactWebView.setLastCommittedUrl(url); reactWebView.callInjectedJavaScriptBeforeContentLoaded(); }