Skip to content

Commit

Permalink
fix(android): custom protocol not triggered on redirect
Browse files Browse the repository at this point in the history
The shouldInterceptRequest function is not called on redirects, which means any redirect to a custom protocol URL will fail to load, so we must apply a small check in the onReceivedError function.

This changes the Android implementation to handle URL load errors to retry loading the URL to give a chance of the custom protocol function to handle the request.
  • Loading branch information
lucasfernog committed Aug 15, 2024
1 parent 5c47758 commit 412ce18
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changes/fix-android-custom-protocol-redirect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"wry": patch
---

Fixes custom protocols not triggered on Android on external redirects.
17 changes: 17 additions & 0 deletions src/android/kotlin/RustWebViewClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

package {{package}}

import android.net.Uri
import android.webkit.*
import android.content.Context
import android.graphics.Bitmap
Expand All @@ -12,6 +13,7 @@ import androidx.webkit.WebViewAssetLoader
class RustWebViewClient(context: Context): WebViewClient() {
private val interceptedState = mutableMapOf<String, Boolean>()
var currentUrl: String = "about:blank"
var lastInterceptedUrl: Uri? = null

private val assetLoader = WebViewAssetLoader.Builder()
.setDomain(assetLoaderDomain())
Expand All @@ -22,6 +24,7 @@ class RustWebViewClient(context: Context): WebViewClient() {
view: WebView,
request: WebResourceRequest
): WebResourceResponse? {
lastInterceptedUrl = request.url
return if (withAssetLoader()) {
assetLoader.shouldInterceptRequest(request.url)
} else {
Expand Down Expand Up @@ -53,6 +56,20 @@ class RustWebViewClient(context: Context): WebViewClient() {
return onPageLoaded(url)
}

override fun onReceivedError(
view: WebView,
request: WebResourceRequest,
error: WebResourceError
) {
// we get a net::ERR_CONNECTION_REFUSED when an external URL redirects to a custom protocol
// e.g. oauth flow, because shouldInterceptRequest is not called on redirects
// so we must force retry here with loadUrl() to get a chance of the custom protocol to kick in
if (error.errorCode == ERROR_CONNECT && request.url != lastInterceptedUrl) {
view.loadUrl(request.url.toString())
} else {
super.onReceivedError(view, request, error)
}
}

companion object {
init {
Expand Down

0 comments on commit 412ce18

Please sign in to comment.