共用方式為


在 WebView2 應用程式中使用框架

框架允許你將其他網頁嵌入到自己的網頁中。 框架是網頁中的子頁或區域,就像網頁中的網頁一樣。

iframe 是一種框架。 其他類型的框架有 framesetportalembedfencedFrameobject、 和 。 WebView2 中主要的框架類型為 CoreWebView2Frame,目前頂層 iframe 已啟用。 計畫支援其他類型的框架。

WebView2 支援 API 來與 iframes 互動。 您可以:

  • 查明 iframe 何時被建立。
  • 找出 iframe 何時會導向不同的網址。 這和 WebView2 應用程式的狀態機導航事件一樣。
  • 主機應用程式與 iframes 之間通訊,雙向傳送訊息。
  • 允許應用程式忽略 X-Frame-Options HTTP 回應標頭。

另請參閱:

訂閱 FrameCreated 事件以取得框架

要與主機應用程式中的框架互動,第一步是訂閱該 FrameCreated 事件,讓主機應用程式取得框架物件。 每當新框架被建立時,事件 FrameCreated 就會被提升。 當你的主機應用程式取得一個框架物件後,利用該框架物件來監控變化並與該特定框架互動。

你的主機應用程式必須透過訂閱 CoreWebView2Frame.Destroyed 事件來監控框架的壽命,因為當框架被銷毀後,主機應用程式就無法再參考該框架。 每次新網頁導覽時,框架會被建立或銷毀。 用這個 CoreWebView2Frame.IsDestroyed 方法檢查畫面是否還存在。

另請參閱:

  • iframesWebView2 API 概述中。

框架建立後,框架會導向該框架的來源網址。 iframes 使用導航與導航事件,例如 FrameNavigationStartingNavigationCompleted和 。 當框架導航至來源 URL 時,會觸發以下導航事件:

  • NavigationStarting
  • ContentLoading
  • HistoryChanged
  • DOMContentLoaded
  • NavigationCompleted

在框架內的導航頻率

導航有可能在一個框架內發生。 作為一個簡單的使用案例, iframe 元素的 source 屬性是 URL,例如 wikipedia.com,URL 會載入在 iframe。 通常導航會在框架建立後立即進行。 ContentLoading DOMContentLoaded NavigationCompleted接著,,以及事件被提出。

框架本身在導航。 網頁會導向網址。 同樣地,框架也可能進行導航。

框架建立後,框架會依照你的主機應用程式驅動來導航。 要監控主頁的動態 NavigationStarting,例如事件,例如 、 NavigationCompleted,並 HistoryChanged 讓主機應用程式能在幀或網頁間來回切換。 框架被導覽到新網址的頻率低於網頁,但支援相同的導航風格。 使用者通常無法在框架內導航,儘管 JavaScript 允許這點;框架在導航方面通常是靜態的。

另請參閱:

導航活動:

關於重複的等價NavigationStartingNavigationCompleted與事件,建議將事件 置CoreWebView2Frame於 ,而非 的等價、被取代事件,CoreWebView2因為該CoreWebView2Frame類型支援更多情境以允許與框架互動。

另請參閱:

在 iframe 中使用主機物件

要在主機應用程式的原生端與 iframe 中的 JavaScript 之間溝通,請使用主機物件。 主機物件是指你在主機應用程式中建立的物件,然後在應用程式網頁端用 JavaScript 程式碼使用。

透過主機物件從框架內的腳本使用原生端 API,類似於網頁/原生互通頁面結構,如 《從網頁端程式碼呼叫原生端程式碼》中所述:

要在 iframe 內使用宿主物件:

  1. 定義主機物件並實作 IDispatch
  2. 在原生端 AddHostObjectToScriptWithOrigins 使用 Win32) 或 AddHostObjectToScript (.NET) 加入主機物件 (。
  3. 從你的網頁端程式碼中的 JavaScript,透過 API 存取這個主機物件 chrome.webview.hostObjects.<name>

若要在框架中存取並控制網頁端 JavaScript 的原生端物件,請使用 AddHostObjectToScriptWithOrigins (Win32) 或 CoreWebView2Frame.AddHostObjectToScript (.NET) ,該參數帶有 origins 參數。 該 origins 參數指定 iframe 可存取哪些 URL,以保障安全。 此參數用以識別 iframes 可存取主機物件的 URL。

如果框架被導向不在 origins 列表中的 URL,框架將無法操作主機物件;框架將無法讀取或寫入任何屬性。 請參閱你的框架中AddHostObjectToScript的方法名稱表。 請參考以下兩列:

  • applyHostFunction、、 getHostPropertysetHostProperty
  • getLocalPropertysetLocalProperty

上述方法如下:

範例程式碼

請參見 步驟 6:呼叫 AddHostObjectToScript,將主機物件傳給網頁端程式碼 ,從 網頁端程式碼呼叫原生端程式碼

另請參閱:

傳送與接收訊息

訊息可以在原生應用程式與 iframe 中的 JavaScript 程式碼之間傳送:

  • 你可以用 JavaScript 在 HTML 頁面的 iframe 發送訊息給主機應用程式。
  • 你可以從主機應用程式發送訊息到 JavaScript,並以 HTML 頁面的 iframe 形式呈現。

從 iframe 傳送網頁訊息到主機應用程式

要從 iframe 傳送網頁訊息到主機應用程式,請使用以下 window.chrome.webview.postMessage 方法:

window.chrome.webview.postMessage(`SetTitleText ${titleText.value}`);

要在主機應用程式中接收這些訊息,主機應用程式必須訂閱 WebMessageReceived event

從主機應用程式向 iframe 傳送訊息

主機應用程式透過呼叫 PostWebMessageAsJson or PostWebMessageAsString 方法向 iframe 發送訊息。

iframe 透過訂閱 window.chrome.webview.addEventListener('message') 事件接收訊息,具體如下:

window.chrome.webview.addEventListener('message', arg => {
    // implement event listener here
});

另請參閱:

使用 ExecuteScript 在 iframe 中執行 JavaScript 程式碼

WebView2 應用程式可透過使用 ExecuteScript

為了讓腳本能在 iframe 中執行,必須建立執行上下文。 執行上下文是在事件發生後 ContentLoading 建立的,因此如果 ExecuteScript 在事件被提出前 ContentLoading 呼叫,腳本不會執行,字串 null 會被回傳。

關於事件 ContentLoading 的資訊,請參閱 WebView2 應用程式的導覽事件,該活動適用於框架與網頁。

另請參閱:

透過使用事件(iframes) WebResourceRequested 來修改網路事件

此功能屬於實驗性質

對於 iframe,你可以監聽網路事件並透過事件 WebResourceRequested 來修改它們。

另請參閱:

請參閱最新的預發布 API。 以下連結包含 1.0.1466-prerelease。 在 API 參考文件左上角的 版本 下拉選單中,選擇最新的預發布版本。

忽略 X-Frame-Options 以在框架內渲染網頁

X-Frame-Options HTTP 回應標頭被網頁用來防止應用程式在框架內渲染該網頁。 這個 AdditionalAllowedFrameAncestors 屬性允許你的應用程式繞過 X-Frame-Options 標頭,將網頁渲染成框架內。

另請參閱:

在主機應用程式中使用 iframes 的範例

這段範例程式碼展示了如何使用框架 API,包括:

  • FrameCreated
    • CoreWebView2FrameCreatedEventArgs
  • DOMContentLoaded
    • CoreWebView2DOMContentLoadedEventArgs
  • ExecuteScript

此範例程式碼是從 WebView2WpfBrowser 範例中的 MainWindow.xaml.cs 精簡而成。

        void DOMContentLoadedCmdExecuted(object target, ExecutedRoutedEventArgs e)
        {
            // Subscribe to the FrameCreated event to obtain the frame object when 
            // it's created.
            webView.CoreWebView2.FrameCreated += WebView_FrameCreatedDOMContentLoaded;
            webView.NavigateToString(@"<!DOCTYPE html>" +
                                      "<h1>DOMContentLoaded sample page</h1>" +
                                      "<h2>The content to the iframe and below will be added after DOM content is loaded </h2>" +
                                      "<iframe style='height: 200px; width: 100%;'/>");
        }

        void WebView_FrameCreatedDOMContentLoaded(object sender, CoreWebView2FrameCreatedEventArgs args)
        {
            // In order for ExecuteScriptAsync to successfully run inside the iframe, 
            // subscribe to the ContentLoading or DOMContentLoaded event.  Once these 
            // events are raised, you can call ExecuteScriptAsync.
            args.Frame.DOMContentLoaded += (frameSender, DOMContentLoadedArgs) =>
            {
                args.Frame.ExecuteScriptAsync(
                    "let content = document.createElement(\"h2\");" +
                    "content.style.color = 'blue';" +
                    "content.textContent = \"This text was added to the iframe by the host app\";" +
                    "document.body.appendChild(content);");
            };
        }

API 參考概述

以下功能列於 WebView2 API 概述中,包含與框架相關的 API:

另請參閱

外部頁面: