WebViewControl.AddInitializeScript(String) Method

Definition

Injects a script into a WebViewControl just after ContentLoading but before any other script is run on the page.

public:
 virtual void AddInitializeScript(Platform::String ^ script) = AddInitializeScript;
void AddInitializeScript(winrt::hstring const& script);
public void AddInitializeScript(string script);
function addInitializeScript(script)
Public Sub AddInitializeScript (script As String)

Parameters

script
String

Platform::String

winrt::hstring

Implements

M:Windows.Web.UI.IWebViewControl2.AddInitializeScript(System.String) M:Windows.Web.UI.IWebViewControl2.AddInitializeScript(Platform::String) M:Windows.Web.UI.IWebViewControl2.AddInitializeScript(winrt::hstring)

Windows requirements

Device family
Windows 10, version 1809 (introduced in 10.0.17763.0)
API contract
Windows.Foundation.UniversalApiContract (introduced in v7.0)

Examples

The following code is a C# sample of script injection on page load:

WebViewControl webViewControl; 

// Replace the window.external with a custom object that does postMessage. The app 
// script uses ScriptNotify and InvokeScriptAsync to implement PostMessage and invoke 
// a messageReceived handler. 
String script = @"var realExternal = window.external;  
var customExternal = { 
    postMessage: (message) => { realExternal.notify('PostMessage: ' + message); }, 
    messageReceived: null, 
}; 
window.external = customExternal;"; 

void ScriptNotifyCallback(WebViewControl sender, WebViewControlScriptNotifyEventArgs args) 
{ 
    String response = GetResponseForPostFromWebView(args.value); 
    sender.InvokeScriptAsync("eval", $"window.external.messageReceived({response});");
} 

webViewControl.ScriptNotify += ScriptNotifyCallback; 
webViewControl.AddInitializeScript(script); 
webViewControl.Navigate(new Uri("http://mydomain.com")); 

Using InvokeScriptAsync, an app can inject scripts into a WebViewControl to provide additional functionality or alter the page. However, InvokeScriptAsync has no guarantees about when the script is executed, and if the app calls it before DOMContentLoaded is raised, there is a risk that the script gets injected into the previous page. This example offers a way for the app to provide a script before navigation (or during NavigationStarting) that will run before any script in the page is executed.

Applies to