Skip to content

Commit

Permalink
feat(android): define WebView class in kotlin (#672)
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasfernog committed Aug 24, 2022
1 parent af7d349 commit b1e8560
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 15 deletions.
5 changes: 5 additions & 0 deletions .changes/webview-class.md
@@ -0,0 +1,5 @@
---
"wry": patch
---

Added the `RustWebView` class on Android.
14 changes: 14 additions & 0 deletions build.rs
Expand Up @@ -50,8 +50,18 @@ fn main() {
.to_string_lossy()
.to_uppercase()
);
let class_init_env = format!(
"WRY_{}_CLASS_INIT",
file
.path()
.file_stem()
.unwrap()
.to_string_lossy()
.to_uppercase()
);

println!("cargo:rerun-if-env-changed={}", class_extension_env);
println!("cargo:rerun-if-env-changed={}", class_init_env);

let content = fs::read_to_string(file.path())
.expect("failed to read kotlin file as string")
Expand All @@ -60,6 +70,10 @@ fn main() {
.replace(
"{{class-extension}}",
&std::env::var(&class_extension_env).unwrap_or_default(),
)
.replace(
"{{class-init}}",
&std::env::var(&class_init_env).unwrap_or_default(),
);

let mut out = String::from("THIS FILE IS AUTO-GENERATED. DO NOT MODIFY!!\n\n");
Expand Down
13 changes: 13 additions & 0 deletions src/webview/android/kotlin/RustWebView.kt
@@ -0,0 +1,13 @@
package {{app-domain-reversed}}.{{app-name-snake-case}}

import android.webkit.*
import android.content.Context

class RustWebView(context: Context): WebView(context) {
init {
this.settings.javaScriptEnabled = true
{{class-init}}
}

{{class-extension}}
}
27 changes: 12 additions & 15 deletions src/webview/android/main_pipe.rs
Expand Up @@ -38,29 +38,26 @@ impl MainPipe<'_> {
match message {
WebViewMessage::CreateWebView(url, initialization_scripts, devtools) => {
// Create webview
let class = env.find_class("android/webkit/WebView")?;
let webview =
env.new_object(class, "(Landroid/content/Context;)V", &[activity.into()])?;

// Enable Javascript
let settings = env
.call_method(
webview,
"getSettings",
"()Landroid/webkit/WebSettings;",
&[],
)?
.l()?;
env.call_method(settings, "setJavaScriptEnabled", "(Z)V", &[true.into()])?;
let rust_webview_class = find_my_class(
env,
activity,
format!("{}/RustWebView", PACKAGE.get().unwrap()),
)?;
let webview = env.new_object(
rust_webview_class,
"(Landroid/content/Context;)V",
&[activity.into()],
)?;

// Load URL
if let Ok(url) = env.new_string(url) {
env.call_method(webview, "loadUrl", "(Ljava/lang/String;)V", &[url.into()])?;
}

// Enable devtools
#[cfg(debug_assertions)]
env.call_static_method(
class,
rust_webview_class,
"setWebContentsDebuggingEnabled",
"(Z)V",
&[devtools.into()],
Expand Down

0 comments on commit b1e8560

Please sign in to comment.