我有一个Windows 10 UWP C#应用程序,它有一个WebView-Control。我正在使用WebView.AddWebAllowedObject方法来注入我自己的JavaScript函数。该类被定义为单独的通用Windows运行时组件项目。然后将本机对象插入OnNavigationStarting事件处理程序中。
在调试模式下一切正常。但是当构建解决方案并在发布模式下运行时,Windows运行时组件在WebView中不起作用,我在输出窗口中看到以下错误
" onecoreuap \ inetcore \ lib \ scriptprojectionhost \ scripthostcontext.cxx(318)\ edgehtml.dll!146477A0 :(来电者:1445B8EE)LogHr(2)tid(3eb8)80004005未指定错误"
以下是我为Windows运行时组件定义类的方法。
[AllowForWeb, ComVisible(true)]
[MarshalingBehavior(MarshalingType.Agile)]
public sealed class MyWebViewHandler : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public event NotifyAppHandler NotifyAppEvent;
public void NotifyPropertyChanged(string info)
{
if (this.PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public void myMouseOverEvent(string webViewEventData)
{
try
{
Href = webViewEventData;
MyWebViewEventData = webViewEventData;
NotifyAppEvent.Invoke(MyWebViewEventData);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
string _myWebViewEventData;
public string MyWebViewEventData
{
get { return this._myWebViewEventData; }
set
{
this._myWebViewEventData = value;
NotifyPropertyChanged("MyWebViewEventData");
}
}
public string Href { get; set; }
}
然后全局初始化运行时对象
public MyWebViewHandler winRTObject = new MyWebViewHandler();
在WebView.NavigationStarting事件处理程序中,我按如下方式调用Webview.InvokeScriptAsync。
myWebView.AddWebAllowedObject("NotifyApp", winRTObject);
在WebView.DOMContentLoaded事件处理程序中,我按如下方式调用Webview.InvokeScriptAsync。
StringBuilder sb = new StringBuilder();
sb.Append("document.addEventListener");
sb.Append("(");
sb.Append("\"mouseover\",");
sb.Append(" function (e) ");
sb.Append("{");
sb.Append(" var attrHref = e.target.getAttribute(\"href\");" +
" NotifyApp.myMouseOverEvent(attrHref);"
);
sb.Append("}");
sb.Append(");");
string function = sb;
await myWebView.InvokeScriptAsync("eval", new[] { function });
该应用曾经在发布模式下正常运行,并于今年早些时候在Windows商店发布。
我不确定此错误是否与Win 10创建者的更新有关。
以下是错误。运行时组件方法未触发。我的开发机器正在运行Window 10 creator update,Visual Studio 2017,15.2(26430.12)
" onecoreuap \ inetcore \ lib \ scriptprojectionhost \ scripthostcontext.cxx(318)\ edgehtml.dll!146477A0 :(来电者:1445B8EE)LogHr(2)tid(3eb8)80004005未指定错误"
非常感谢任何输入。
为NotifyAppHandler和PropertyChangedEventHandler添加相关代码
winRTObject.PropertyChanged += WinRTObject_PropertyChanged;
winRTObject.NotifyAppEvent += WinRTObject_NotifyAppEvent;
...
private void WinRTObject_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
try
{
string elementValue = winRTObject.Href
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
private void WinRTObject_NotifyAppEvent(string eventData)
{
try
{
string elementValue = eventData;
...
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
更新1
我降级了NuGet包" Microsoft.NetCore.UniversalWindowsPlatform"从版本5.3.4到5.2.3,问题得到了解决。
注意:Visual Studio 2017,15.2(26430.12)在Blank UWP App模板中包含5.2.3。