是的,您可以使用 jQuery,但是您只能在 DOM 完全加载后才能使用它。为此,您需要使用 WebView 的 PropertyChanged 事件来检查 IsLoading 属性何时更改为 false 并且 IsBrowserInitialized 属性设置为 true。
请参阅下面的片段,了解我如何在我的一个项目中做到这一点。正如你所看到的,一旦 IsLoading 属性发生变化,我就会调用一些方法来设置 WebView 中的内容,这是通过 ExecuteScript 调用 jQuery 来完成的。
/// <summary>
/// Initialise the WebView control
/// </summary>
private void InitialiseWebView()
{
// Disable caching.
BrowserSettings settings = new BrowserSettings();
settings.ApplicationCacheDisabled = true;
settings.PageCacheDisabled = true;
// Initialise the WebView.
this.webView = new WebView(string.Empty, settings);
this.WebView.Name = string.Format("{0}WebBrowser", this.Name);
this.WebView.Dock = DockStyle.Fill;
// Setup and regsiter the marshal for the WebView.
this.chromiumMarshal = new ChromiumMarshal(new Action(() => { this.FlushQueuedMessages(); this.initialising = false; }));
this.WebView.RegisterJsObject("marshal", this.chromiumMarshal);
// Setup the event handlers for the WebView.
this.WebView.PropertyChanged += this.WebView_PropertyChanged;
this.WebView.PreviewKeyDown += new PreviewKeyDownEventHandler(this.WebView_PreviewKeyDown);
this.Controls.Add(this.WebView);
}
/// <summary>
/// Handles the PropertyChanged event of CefSharp.WinForms.WebView.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The event arguments.</param>
private void WebView_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
// Once the browser is initialised, load the HTML for the tab.
if (!this.webViewIsReady)
{
if (e.PropertyName.Equals("IsBrowserInitialized", StringComparison.OrdinalIgnoreCase))
{
this.webViewIsReady = this.WebView.IsBrowserInitialized;
if (this.webViewIsReady)
{
string resourceName = "Yaircc.UI.default.htm";
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
{
using (StreamReader reader = new StreamReader(stream))
{
this.WebView.LoadHtml(reader.ReadToEnd());
}
}
}
}
}
// Once the HTML has finished loading, begin loading the initial content.
if (e.PropertyName.Equals("IsLoading", StringComparison.OrdinalIgnoreCase))
{
if (!this.WebView.IsLoading)
{
this.SetSplashText();
if (this.type == IRCTabType.Console)
{
this.SetupConsoleContent();
}
GlobalSettings settings = GlobalSettings.Instance;
this.LoadTheme(settings.ThemeFileName);
if (this.webViewInitialised != null)
{
this.webViewInitialised.Invoke();
}
}
}
}