WebView.AddWebAllowedObject(String, Object) 方法

定義

將原生Windows 執行階段物件當做全域參數新增至WebView內的最上層檔。

public:
 virtual void AddWebAllowedObject(Platform::String ^ name, Platform::Object ^ pObject) = AddWebAllowedObject;
void AddWebAllowedObject(winrt::hstring const& name, IInspectable const& pObject);
public void AddWebAllowedObject(string name, object pObject);
function addWebAllowedObject(name, pObject)
Public Sub AddWebAllowedObject (name As String, pObject As Object)

參數

name
String

Platform::String

winrt::hstring

要公開至 WebView中檔的物件名稱。

pObject
Object

Platform::Object

IInspectable

要公開至 WebView中檔的物件。

範例

此範例示範如何使用 AllowForWeb 屬性裝飾類別。

using Windows.Foundation.Metadata;

namespace MyRuntimeComponent
{
    [AllowForWeb]
    public sealed class MyNativeClass
    {
        public void NativeMethod()
        {
            ...
        }

        ...
    }
}

這個範例示範如何使用 NavigationStarting 事件,在導覽開始時插入物件。

<WebView x:Name="webView" Source="https://www.contoso.com/index.html"
         NavigationStarting="webView_NavigationStarting"/>
private void webView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args) 
{ 
    if (args.Uri.Host == "www.contoso.com")  
    { 
        webView.AddWebAllowedObject("nativeObject", new MyNativeClass()); 
    } 
} 

以下是如何在網頁的腳本中存取原生物件。

<script type='text/javascript'>
    nativeObject.nativeMethod(); // Call the projected WinRT method.
</script>

備註

使用這個方法,將原生Windows 執行階段物件公開為WebView內最上層檔內容中的全域參數。 若要投影Windows 執行階段物件,它必須敏捷且使用AllowForWeb屬性裝飾。

注意

根據預設,使用 Microsoft Visual Basic、C# 或 Visual C++ 元件延伸模組建立的執行時間類別 (C++/CX) 是敏捷式的。 如需詳細資訊,請參閱執行緒和封送處理和在多執行緒環境中使用 Windows 執行階段 物件

傳遞至 AddWebAllowedObject 的物件必須從與應用程式元件分開的Windows 執行階段元件匯入。 這是由WebView安全性子系統識別的 AllowForWeb屬性的必要專案。 如果您使用來自應用程式專案的類別,AddWebAllowedObject 將無法運作。

每次 WebView 巡覽至存取原生物件的新頁面時,您必須呼叫 AddWebAllowedObject。 您可以使用 WebView.NavigationStarting 事件,在導覽開始時插入物件。

適用於