add javascript interface to android webView so messages can be sent from web to android

This commit is contained in:
Satindar Dhillon 2022-09-22 20:57:29 -07:00
parent 0f1607e61c
commit 1d619dda5d
6 changed files with 32 additions and 12 deletions

View file

@ -10,6 +10,7 @@ apple_extension_gen:
droid:
studio android/Omnivore
apple_webview_gen:
webview_gen:
yarn workspace @omnivore/appreader build
cp packages/appreader/build/bundle.js apple/OmnivoreKit/Sources/Views/Resources/bundle.js
cp packages/appreader/build/bundle.js android/Omnivore/app/src/main/assets/bundle.js

File diff suppressed because one or more lines are too long

View file

@ -5,6 +5,7 @@ import android.content.Context
import android.graphics.Rect
import android.util.Log
import android.view.*
import android.webkit.JavascriptInterface
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.compose.material3.Text
@ -13,6 +14,8 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.viewinterop.AndroidView
import app.omnivore.omnivore.R
import org.json.JSONObject
@Composable
fun WebReaderLoadingContainer(slug: String, webReaderViewModel: WebReaderViewModel) {
@ -63,6 +66,7 @@ fun WebReader(params: WebReaderParams) {
webViewClient = object : WebViewClient() {
}
addJavascriptInterface(WebMessageHandler(), "WebMessageHandler")
loadDataWithBaseURL("file:///android_asset/", styledContent, "text/html; charset=utf-8", "utf-8", null);
}
@ -133,3 +137,14 @@ class OmnivoreWebView(context: Context) : WebView(context) {
return super.startActionMode(currentActionModeCallback, type)
}
}
class WebMessageHandler {
@JavascriptInterface
fun handleMessage(jsonString: String) {
val message = JSONObject(jsonString)
Log.d("Loggo", "Handling message: $message")
val actionID = message["actionID"]
Log.d("Loggo", "Received message with ID: $actionID and jsonValue: $message")
}
}

View file

@ -104,8 +104,6 @@ data class WebReaderContent(
</html>
"""
Log.d("Loggos", content)
return content
}
}

File diff suppressed because one or more lines are too long

View file

@ -7,13 +7,19 @@ import '@omnivore/web/styles/globals.css'
import '@omnivore/web/styles/articleInnerStyling.css'
const mutation = async (name, input) => {
const result =
await window?.webkit?.messageHandlers.articleAction?.postMessage({
actionID: name,
...input,
})
console.log('action result', result, result.result)
return result.result
const message = { actionID: name, ...input }
if (window.webkit) {
// Send iOS a message
const result =
await window?.webkit?.messageHandlers.articleAction?.postMessage(message)
console.log('action result', result, result.result)
return result.result
} else {
// Send android a message
console.log('sending android a message', message)
WebMessageHandler.handleMessage(JSON.stringify(message))
}
}
const App = () => {