WebViewControl.AddInitializeScript(String) 方法

定义

ContentLoading 之后、页面上运行任何其他脚本之前,将脚本注入 WebViewControl

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)

参数

script
String

Platform::String

winrt::hstring

实现

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 要求

设备系列
Windows 10, version 1809 (在 10.0.17763.0 中引入)
API contract
Windows.Foundation.UniversalApiContract (在 v7.0 中引入)

示例

以下代码是页面加载时脚本注入的 C# 示例:

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")); 

使用 InvokeScriptAsync,应用可以将脚本注入 WebViewControl 以提供其他功能或更改页面。 但是,InvokeScriptAsync 无法保证脚本的执行时间,如果应用在引发 DOMContentLoaded 之前调用脚本,则存在脚本被注入上一页的风险。 此示例提供了一种方法,使应用在导航 (之前或在 NavigationStarting) 中提供脚本,该脚本在执行页面中的任何脚本之前将运行。

适用于