Skip to content

Latest commit

 

History

History
51 lines (38 loc) · 2.24 KB

webviewcontrol_addinitializescript_585591006.md

File metadata and controls

51 lines (38 loc) · 2.24 KB
-api-id -api-type ms.custom
M:Windows.Web.UI.Interop.WebViewControl.AddInitializeScript(System.String)
winrt method
RS5

Windows.Web.UI.Interop.WebViewControl.AddInitializeScript

-description

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

-parameters

-param script

-remarks

-see-also

-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.