このページは機械翻訳のため、誤りを含む場合があります。 英語の原文を読む

要素

WebView

Web ビューは、Web ページまたは渡した HTML をアプリ内に表示します。iOS と Mac Catalyst では WKWebView、Android では android.webkit.WebView を使います。NSH はネイティブビューでレンダリングするため、Web ビューは他のビューと同様にレイアウトに配置され、周囲のビューと順序どおりに並びます。Rust では web_view(url) または web_view_html(html, base_url) で、TSX では nsh の <WebView> で作成します。

el-web-view.tsx
el-web-view.tsxLive
import { mount, signal, Text, View, WebView, type WebViewNavigation, type WebViewRef } from "nsh";
import { platform, windowSize } from "nsh";
import { button, buttonText, ui } from "./palette";

// The page: a button that posts to the app, and a line that shows what the
// app posts back.
const page = (c: ReturnType<typeof ui>) => `<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Inline page</title>
<style>
  body { font: 15px system-ui, sans-serif; margin: 0; padding: 16px; background: ${c.page}; color: ${c.text}; }
  button { font: inherit; font-weight: 600; padding: 10px 14px; border-radius: 10px; border: 1px solid ${c.border}; background: ${c.accent}; color: ${c.page}; }
  .muted { color: ${c.muted}; }
  #got { margin-top: 12px; }
  #box { margin-top: 12px; height: 48px; border-radius: 10px; background: ${c.border}; transition: background 0.3s; }
</style>
<p class="muted">This is HTML in a web view.</p>
<button id="post">postMessage to the app</button>
<p id="got" class="muted">Nothing from the app yet.</p>
<div id="box"></div>
<script>
  let taps = 0;
  document.getElementById("post").onclick = () =>
    window.nsh.postMessage("tap " + ++taps + " from the page");
  window.addEventListener("message", (e) => { document.getElementById("got").textContent = "App says: " + e.data; });
</script>`;

function Button(props: { label: string; onPress: () => void }) {
  return (
    <View
      onPress={props.onPress}
      {...button()}
    >
      <Text style={buttonText()}>{props.label}</Text>
    </View>
  );
}

const colors = () => [ui().accent, ui().info, ui().violet, ui().down, ui().warn];

function App() {
  const messages = signal<string[]>([]);
  const nav = signal<WebViewNavigation | null>(null);
  const sent = signal(0);
  let painted = 0;
  let web!: WebViewRef;
  const wide = () => windowSize().width >= 700;

  return (
    <View style={{ flex: 1, backgroundColor: ui().page, padding: 20, paddingTop: 24, gap: 14 }}>
      <Text style={{ fontSize: 22, fontWeight: "700", color: ui().text }}>web-view</Text>
      <View style={{ flex: 1, flexDirection: wide() ? "row" : "column", gap: 16 }}>
        <WebView
          ref={web}
          html={page(ui())}
          // Runs after each load: the page reports its title.
          injectedJavaScript={`window.nsh.postMessage("loaded: " + document.title)`}
          onLoad={(e) => nav.set(e)}
          onMessage={(e) => messages.set([e.data, ...messages()].slice(0, 4))}
          style={{ flex: 1, minHeight: 240, borderRadius: 14, overflow: "hidden", borderWidth: 1, borderColor: ui().border }}
        />
        <View style={{ gap: 12, width: wide() ? 320 : undefined }}>
          <Text style={{ color: ui().muted }}>
            {platform.desktop ? "Click" : "Tap"} the button in the page to post to the app; these buttons call the ref's methods.
          </Text>
          <View style={{ flexDirection: "row", flexWrap: "wrap", gap: 8 }}>
            <Button
              label="postMessage"
              onPress={() => {
                sent.update((n) => n + 1);
                web.postMessage(`hello #${sent()}`);
              }}
            />
            <Button
              label="injectJavaScript"
              onPress={() => {
                const color = colors()[painted++ % colors().length];
                web.injectJavaScript(`document.getElementById("box").style.background = "${color}"`);
              }}
            />
            <Button label="reload" onPress={() => web.reload()} />
          </View>
          <View style={{ ...ui().card, borderRadius: 12, padding: 12, gap: 4 }}>
            <Text style={{ color: ui().muted, fontSize: 12 }}>onLoad</Text>
            <Text style={{ numberOfLines: 1, color: ui().text, fontFamily: "monospace", fontSize: 13 }}>
              {nav() ? `title "${nav()!.title}"` : "…"}
            </Text>
            <Text style={{ color: ui().muted, fontSize: 12, marginTop: 6 }}>onMessage, newest first</Text>
            <Each of={messages()}>
              {(m) => <Text style={{ color: ui().text, fontFamily: "monospace", fontSize: 13 }}>{m()}</Text>}
            </Each>
          </View>
        </View>
      </View>
    </View>
  );
}

mount(App);
use nsh_core::prelude::*;

fn browser() -> impl IntoElement {
    let title = signal(SharedString::from("Loading…"));
    view()
        .flex_1()
        .child(text(title).number_of_lines(1))
        .child(
            web_view("https://example.com")
                .flex_1()
                .on_navigation_state_change(move |e: &WebNavigation| title.set(e.title.clone().into())),
        )
}

TSX では、Web ビューは src と html のいずれか一方を受け取ります(WebView API を参照)。Web ビューと動画のガイドでは、メッセージングのパターンと capabilities を扱っています。

#Props

Web ビューは view の Props(子要素は持ちません)に加えて、次の Props を受け取ります。

PropRust型デフォルト説明
srcweb_view(url)string表示するページの URL。
htmlweb_view_html(html, base_url)、.html(html, base_url)stringインライン HTML。src の代わりに表示されます。
baseUrlweb_view_html / .html の base_urlstringhtml 内の相対リンクの解決基準。
injectedJavaScript.injected_java_script(..)string各ページの読み込み後に実行されます。
injectedJavaScriptBeforeContentLoaded.injected_java_script_before_content(..)string各ページ自身のスクリプトより前に実行されます。
userAgent.user_agent(..)stringブラウザーのユーザーエージェント文字列。
javaScriptEnabled.java_script_enabled(..)booleantrueページでスクリプトを実行します。
scrollable.scrollable(..)booleantrueユーザーがページをスクロールできます。
ios キーRust型説明
allowsBackForwardNavigationGestures.back_forward_gestures(..)boolean画面の端からスワイプして、戻る・進むを行います。
desktop キーRust型説明
allowsBackForwardNavigationGestures.back_forward_gestures(..)booleanmacOS: トラックパッドで2本指でスワイプして、戻る・進むを行います。Windows: タッチスクリーンでスワイプします。Linux: タッチパッドでスワイプします。

#Events

イベントRustペイロード発生タイミング
onLoadStart.on_load_startWebViewNavigationページの読み込みが開始されたとき。
onLoad.on_loadWebViewNavigationページの読み込みが完了したとき。
onError.on_error{ message, code? }(&str、メッセージ)読み込みに失敗したとき。code は、ページの場合は "ERR_ACCESS_DENIED"、アプリの capabilities が許可していないものの場合は html になります。
onNavigationStateChange.on_navigation_state_changeWebViewNavigationURL、タイトル、読み込み状態、または履歴が変化したとき。
onMessage.on_message{ data: string }(&str)ページが window.nsh.postMessage(data) を呼び出したとき。
onDownloadWebViewDownloadダウンロードが開始、完了、または失敗したとき(macOS)。

WebViewNavigation は { url, title, loading, canGoBack, canGoForward } です。Rust では WebNavigation で、url、title、loading、can_go_back、can_go_forward を持ちます。

WebViewDownload は { state, id, url, filename, path, bytes?, message? } です。state は "started"、"finished"(ファイルの bytes を伴う)、または "failed"(その message を伴う)のいずれかです。onDownload リスナーがある場合、ページがダウンロードするもの(添付ファイル、Web ビューが表示しない種類のもの、download リンク)は、アプリのデータディレクトリに downloads/<id>/<filename> として保存されます。path はその保存先を指し、アプリは fs/promises で読み取ります。

macOS では、リスナーを追加すると、webview capability で許可されている読み込み済みのどのページでも、ダウンロードが自動的に保存されるようになります。ストレージの使用量の管理と、使い終えた完了済みファイルの downloads/ からの削除は、アプリの責任です。Web ビューを削除すると、進行中のダウンロードはキャンセルされ、その一時ディレクトリも削除されます。ダウンロードは onDownload を通じて報告されます。ナビゲーションをダウンロードに変換した場合、onError は実際のナビゲーション失敗のために残されます。ファイル名からは制御文字と双方向書式制御文字が取り除かれ、長い名前は、収まる拡張子を保持したまま 200 バイトに短縮されます。

#Ref methods

メソッドRust説明
reload()reload()ページを再読み込みします。
goBack() / goForward()go_back() / go_forward()ページの履歴内を移動します。
stopLoading()stop_loading()読み込みを停止します。
injectJavaScript(script)inject_java_script(script)ページ内で JavaScript を実行します。
postMessage(data)post_message(data)ページに文字列を送信します。ページは window で message イベントを受け取ります。

#Messaging

アプリとページは文字列をやり取りします。ページは window.nsh.postMessage(data) で送信し、アプリは ref の postMessage(data)(Rust では post_message(..))で送信します。構造化データを送るには JSON を使用してください。

use nsh_core::prelude::*;

const PAGE: &str = r#"<!doctype html>
<meta name="viewport" content="width=device-width">
<button onclick="window.nsh.postMessage('hello from the page')">Post to the app</button>
<p id="got"></p>
<script>
  window.addEventListener("message", (e) => { document.getElementById("got").textContent = e.data; });
</script>"#;

fn bridge() -> impl IntoElement {
    let message = signal(String::new());
    let web = element_ref();
    view()
        .gap_3()
        .child(
            web_view_html(PAGE.to_string(), None)
                .element_ref(&web)
                .h(px(200.0))
                .on_message(move |data: &str| message.set(data.to_string())),
        )
        .child(
            text(move || format!("Post to the page · got: {}", message.get()))
                .on_press(move || web.post_message("hi from the app")),
        )
}

#Capabilities

アプリが nsh.json で capabilities を宣言している場合、Web ビューは webview に列挙されたホストを表示し、そこへナビゲートします。他のホストの src、または webview のないアプリでの html は、空のビューを表示します。他のホストへのトップレベルのナビゲーション(ユーザーがタップしたリンクなど)は、ネイティブ側でキャンセルされます。いずれの場合も、code "ERR_ACCESS_DENIED" とともに onError が報告されます。

{
  "capabilities": {
    "webview": { "hosts": ["example.com", "*.example.com"] }
  }
}

#Platform notes

  • iOS では、Web ビューが最初に作成されるときに WebKit が読み込まれるため、アプリにコストが生じるのは Web ビューを表示したときだけです。
  • macOS では、onDownload は WebKit の WKDownload でダウンロードを保存します。
  • Android では、ページからの postMessage 呼び出しはバックグラウンドスレッドで届き、順序どおりにアプリへ転送されます。
  • Web ビューの角を丸めるには、角丸の半径と overflow: "hidden"(.overflow_hidden())を指定します。