WebView.AddWebAllowedObject(String, Object) WebView.AddWebAllowedObject(String, Object) WebView.AddWebAllowedObject(String, Object) WebView.AddWebAllowedObject(String, Object) Method

Definition

Adds a native Windows Runtime object as a global parameter to the top level document inside of a WebView.

public : void AddWebAllowedObject(Platform::String name, Platform::Object pObject)
void AddWebAllowedObject(winrt::hstring name, winrt::Windows::Foundation::IInspectable pObject) const;
public void AddWebAllowedObject(String name, Object pObject)
Public Sub AddWebAllowedObject(name As String, pObject As Object)
Parameters
name
String String

The name of the object to expose to the document in the WebView.

pObject
Object Object

The object to expose to the document in the WebView.

Examples

This example shows how to decorate a class with the AllowForWeb attribute.

using Windows.Foundation.Metadata;

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

        ...
    }
}

This example demonstrates using the NavigationStarting event to inject an object when navigation begins.

<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()); 
    } 
} 

Here's how to access the native object in a script in the web page.

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

Remarks

Use this method to expose a native Windows Runtime object as a global parameter in the context of the top level document inside of a WebView. For a Windows Runtime object to be projected, it must agile and be decorated with the AllowForWeb attribute.

Note

Runtime classes created using Microsoft Visual Basic, C# or Visual C++ component extensions (C++/CX) are agile by default. For more info, see Threading and Marshaling and Using Windows Runtime objects in a multithreaded environment.

The object passed into AddWebAllowedObject must be imported from a Windows Runtime component that is separate from the app assembly. This is necessary for the AllowForWeb attribute to be property identified by the WebView security subsystem. If you use a class from your app project, AddWebAllowedObject does not work.

You must call AddWebAllowedObject every time WebView is navigated to a new page that accesses the native object. You can use the WebView.NavigationStarting event to inject the object when navigation begins.