如何在WP7 WebBrowser控件中注入Javascript?

我可以通过此链接在C#窗体中的WebBrowser控件中注入JavaScript

如何在WebBrowser控件中注入JavaScript?

但我不能在WP7中这样做,请帮助我。

遗憾的是,WP7上没有WebBrowser.Document 。 但您可以使用InvokeScript创建和调用JavaScript函数。 看看我在哪里描述如何。

简而言之:您不使用.Document和C#,而是创建一段JavaScript。 然后使用此脚本作为参数调用eval以调用它。 像这样:

 webBrowser1.InvokeScript("eval", " ...code goes here... "); 

对于桌面WebBrowser (WinForms / WPF), InvokeScript("eval", ...)的网页上必须至少有一个标记才能InvokeScript("eval", ...) 。 即,如果页面不包含任何JavaScript(例如 ),则eval不能正常工作。

我没有安装Windows Phone SDK /模拟器来validationWindows Phone WebBrowser是否也是这种情况。

不过,以下适用于Windowsapp store应用。 诀窍是使用this.webBrowser.InvokeScript("setTimeout", ...)首先注入一些JavaScript。 我正在使用它而不是自IE11以来不推荐使用的execScript

 async void MainPage_Loaded(object sender, RoutedEventArgs e) { // load a blank page var tcsLoad = new TaskCompletionSource(); this.webBrowser.NavigationCompleted += (s, eArgs) => tcsLoad.TrySetResult(Type.Missing); this.webBrowser.NavigateToString(""); await tcsLoad.Task; // first add a script via "setTimeout", JavaScript gets initialized var tcsInit = new TaskCompletionSource(); this.webBrowser.ScriptNotify += (s, eArgs) => { if (eArgs.Value == "initialized") tcsInit.TrySetResult(Type.Missing); }; this.webBrowser.InvokeScript("setTimeout", new string[] { "window.external.notify('initialized')", "0" }); await tcsInit.Task; // then use "eval" this.webBrowser.InvokeScript("eval", new string[] { "document.body.style.backgroundColor = 'yellow'" }); } 

如果有人能够确认WP WebBrowser是否有效,我将不胜感激。 在上面的代码中, LoadCompleted应该用于WP而不是NavigationCompleted ,并且WebBrowser.IsScriptEnabled必须设置为true

Interesting Posts