CefSharp 'CanExecuteJavascriptInMainFrame' false after page loaded async - winforms

I found error while using LoadPageAsync Method.
All code to reproduce is below.
1) Wait while new ChromiumWebBrowser("https://www.google.com/") page loaded.
2) then press button1.
Result: canExecuteJs will be false while canExecuteJs1 will be true.
In other hand if don't wait for new ChromiumWebBrowser("https://www.google.com/") page to be loaded, and in moment button appear on screen click it, both variables will be true.
public ChromiumWebBrowser chromeBrowser;
public Form1()
{
InitializeComponent();
Cef.EnableHighDPISupport();
Cef.Initialize(settings);
chromeBrowser = new ChromiumWebBrowser("https://www.google.com/");
Controls.Add(chromeBrowser);
chromeBrowser.Dock = DockStyle.Fill;
}
public Task LoadPageAsync(IWebBrowser browser, string address = null)
{
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
EventHandler<LoadingStateChangedEventArgs> handler = null;
handler = (sender, args) =>
{
if (!args.IsLoading)
{
browser.LoadingStateChanged -= handler;
tcs.TrySetResult(true);
}
};
browser.LoadingStateChanged += handler;
if (!string.IsNullOrEmpty(address))
browser.Load(address);
return tcs.Task;
}
private async void button1_Click(object sender, EventArgs e)
{
await LoadPageAsync(chromeBrowser, "https://stackoverflow.com/questions/59862329/wordpress-submit-form-into-new-tab-and-continue-processing");
var canExecuteJs = chromeBrowser.CanExecuteJavascriptInMainFrame; //FALSE
await LoadPageAsync(chromeBrowser, "https://stackoverflow.com/questions/59861819/getting-2-values-from-array-of-objects");
var canExecuteJs1 = chromeBrowser.CanExecuteJavascriptInMainFrame; //TRUE
}

Related

WPF C# Cefsharp Ver. 71, each load of user control creates new CefSharp.BrowserSubprocess.exe

Please check the code snippets below, this get loaded everytime i navigate to my view(user control) and it creates new CefSharp.BrowserProcess.exe on each load and renders last visited URL.
Problem with is is that it does not maintain the session storage of the site (URL) And load is incorrect with data is lost.
viewModel (main) code:
private void OnLoad()
{
IsBusy = true;
try
{
if (string.IsNullOrEmpty(TieAddress))
{
TieAddress = _serviceJournalsBaseSettings.GetTieUrl();
}
var cookieManager = Cef.GetGlobalCookieManager();
Cookie cookie = new Cookie
{
Name = BaseSettings.GetTieCookieName(),
Value = BaseSettings.GetTieCookie()
};
cookieManager.SetCookie(BaseSettings.GetTieCookieUrl(), cookie);
}
catch (Exception ex)
{
ShowErrorNotification(ex.Message);
}
finally
{
IsBusy = false;
}
}
View (User control) Code:
<wpf:ChromiumWebBrowser
Grid.Row="1" Grid.ColumnSpan="2"
x:Name="BrowserTieView"
Address="{Binding TieAddress, Mode=TwoWay}"
Title="Browser Tie View"
AllowDrop="True"/>
View.Xaml.cs
public partial class ServiceJournalsView : UserControl
{
public ServiceJournalsView()
{
InitializeComponent();
BrowserTieView.DownloadHandler = new DownloadHandler();
BrowserTieView.BrowserSettings = new BrowserSettings()
{
ApplicationCache = CefState.Enabled,
FileAccessFromFileUrls = CefState.Enabled,
Javascript = CefState.Enabled,
LocalStorage = CefState.Enabled,
WebSecurity = CefState.Disabled,
JavascriptCloseWindows = CefState.Enabled,
JavascriptDomPaste = CefState.Enabled,
};
BrowserTieView.LoadError += (sender, args) =>
{
// Don't display an error for downloaded files.
if (args.ErrorCode == CefErrorCode.Aborted)
{
return;
}
// Display a load error message.
var errorBody = string.Format(
"<html><body bgcolor=\"white\"><h2>Failed to load URL {0} with error {1} ({2}).</h2></body></html>",
args.FailedUrl, args.ErrorText, args.ErrorCode);
args.Frame.LoadHtml(errorBody, base64Encode: true);
};
Unloaded += async delegate (object sender, RoutedEventArgs args)
{
BrowserTieView.WebBrowser.Dispose();
BrowserTieView.Dispose();
await Task.Delay(10);
};
}
public ServiceJournalsViewModel VMServiceJournalsViewModel
{
get => (ServiceJournalsViewModel) DataContext;
set { DataContext = value; }
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
try
{
BrowserTieView.RegisterJsObject("serviceJournalsJsModel", VMServiceJournalsViewModel.ServiceJournalsJsModel);
}
catch (Exception ex)
{
}
}
}
As per discussion in the comments of the question posted( and as per #amaitland) Multiple instances of Cefsharp.BrowserSubprocess.exe is perfectly normal.

WebKit.NET C# Custom Context Menu

I am implementing a Webkit Browser control in my windows app.
I need to use a custom context menu (right click) that only has copy/cut/paste as its options regardless of what element is right clicked. I need kind of a step-by-step as to how to implement it
Customizing the context menu for the WebKitBrowser supposes that you get a reference to the WebViewClass and then, setting a IWebUIDelegate for it by calling the setUIDelegate() method.
void MyWebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var webView = this.GetWebView() as WebKit.Interop.WebViewClass;
webView.setUIDelegate(new MyWebUIDelegate(this));
}
In the IWebUIDelegate implementation you may intercept the contextMenuItemsForElement method and trigger the display of the context menu of the browser.
Here is a working sample:
public partial class Form1 : Form
{
MyWebBrowser webKitBrowser;
public Form1()
{
InitializeComponent();
webKitBrowser = new MyWebBrowser();
webKitBrowser.Dock = DockStyle.Fill;
this.Controls.Add(webKitBrowser);
webKitBrowser.Navigate("http://www.google.com");
}
}
class MyContextMenu : ContextMenu
{
public MyContextMenu()
{
var cutMenuItem = new MenuItem("Cut");
var copyMenuItem = new MenuItem("Copy");
var pasteMenuItem = new MenuItem("Paste");
cutMenuItem.Click += cutMenuItem_Click;
MenuItems.Add(cutMenuItem);
MenuItems.Add(copyMenuItem);
MenuItems.Add(pasteMenuItem);
}
void cutMenuItem_Click(object sender, EventArgs e)
{
//TODO: implement functionality
MessageBox.Show("Cut was selected");
}
}
class MyWebBrowser : WebKitBrowser
{
public event EventHandler ShowContextMenu = new EventHandler(OnFireShowContextMenu);
public MyWebBrowser()
{
DocumentCompleted += MyWebBrowser_DocumentCompleted;
var myContextMenu = new MyContextMenu();
ContextMenu = myContextMenu;
}
void MyWebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var webView = this.GetWebView() as WebKit.Interop.WebViewClass;
webView.setUIDelegate(new MyWebUIDelegate(this));
}
public static void OnFireShowContextMenu(object sender, EventArgs e)
{
var webBrowser = (Control)sender;
var webView = (WebKit.Interop.WebViewClass)((MyWebBrowser)sender).GetWebView();
var originalPoint = webBrowser.PointToScreen(new Point(0, 0));
var currentPoint = new Point(Cursor.Position.X - originalPoint.X, Cursor.Position.Y - originalPoint.Y);
((WebKitBrowser)sender).ContextMenu.Show((Control)sender, currentPoint);
}
public void FireShowContextMenu()
{
this.ShowContextMenu(this, null);
}
}
class MyWebUIDelegate : IWebUIDelegate
{
private MyWebBrowser owner;
public MyWebUIDelegate(MyWebBrowser browser)
{
this.owner = browser;
}
//trigger the browser's FireShowContextMenu() method
public int contextMenuItemsForElement(WebView sender, CFDictionaryPropertyBag element, int defaultItemsHMenu)
{
owner.FireShowContextMenu();
return defaultItemsHMenu;
}
//return 1, true
public int hasCustomMenuImplementation()
{
return 1;
}
//the rest of the IWebUIDelegate interface implementation
}
For more insight, probably you would want to study some other customizations, such as open-webkit-sharp.

how to close all the open form in WPF

In my Application I have two buttons "open" and "close".
When I click open button window will be opened, when I click close button window will be closed.
When I click open button 3 times, 3 windows will be opened. I want to close all window when I click close button.
Here is my code [Please don't try to Change the Thread because that is my requirement in my Application]
public partial class MainWindow : Window
{
Window ProgressWindow;
Thread ProgressThread;
public MainWindow()
{
InitializeComponent();
}
private void Open_Click(object sender, RoutedEventArgs e)
{
ProgressThread = new Thread(() =>
{
ProgressWindow = new Window();
ProgressWindow.Margin = new Thickness(0, 0, 50, 0);
ProgressWindow.WindowState = WindowState.Normal;
ProgressWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
ProgressWindow.Height = 180;
ProgressWindow.Width = 180;
ProgressWindow.Content = "Hello WPF";
ProgressWindow.ShowInTaskbar = false;
ProgressWindow.Show();
ProgressWindow.Closed += (sender2, e2) =>
ProgressWindow.Dispatcher.InvokeShutdown();
System.Windows.Threading.Dispatcher.Run();
});
ProgressThread.SetApartmentState(ApartmentState.STA);
ProgressThread.Start();
}
private void Close_Click(object sender, RoutedEventArgs e)
{
if (ProgressThread.IsAlive == true)
{
ProgressThread.Abort();
}
}
}
I would recommend to store references to created windows, your code can look like this:
Stack<Window> ProgressWindow=new Stack<Window>();
Thread ProgressThread;
private void Open_Click(object sender, RoutedEventArgs e)
{
ProgressThread = new Thread(() =>
{
var window = new Window();
window.Margin = new Thickness(0, 0, 50, 0);
window.WindowState = WindowState.Normal;
window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
window.Height = 180;
window.Width = 180;
window.Content = "Hello WPF";
window.ShowInTaskbar = false;
window.Show();
window.Closed += (sender2, e2) =>
window.Dispatcher.InvokeShutdown();
ProgressWindow.Push(window);
System.Windows.Threading.Dispatcher.Run();
});
ProgressThread.SetApartmentState(ApartmentState.STA);
ProgressThread.Start();
}
private void Close_Click(object sender, RoutedEventArgs e)
{
while (ProgressWindow.Count > 0)
{
ProgressWindow.Pop().Close();
}
}
thread aborting is not recommended if it is "normal" workflow of your application, i.e. window wasn't closed because of some critical error
I wouldn't recommend what you are doing and actually I don't really know if it works like this, but since you stated that it's your (strange) requirement to use threads like this, I will only comment on the actual problem:
You should save the threads in a List and then close all the threads from this list.
Edit:
public partial class MainWindow : Window
{
Window ProgressWindow;
List<Thread> ProgressThreads = new List<Thread>();
public MainWindow()
{
InitializeComponent();
}
private void Open_Click(object sender, RoutedEventArgs e)
{
ProgressThreads.Add(new Thread(() =>
{
ProgressWindow = new Window();
ProgressWindow.Margin = new Thickness(0, 0, 50, 0);
ProgressWindow.WindowState = WindowState.Normal;
ProgressWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
ProgressWindow.Height = 180;
ProgressWindow.Width = 180;
ProgressWindow.Content = "Hello WPF";
ProgressWindow.ShowInTaskbar = false;
ProgressWindow.Show();
ProgressWindow.Closed += (sender2, e2) =>
ProgressWindow.Dispatcher.InvokeShutdown();
System.Windows.Threading.Dispatcher.Run();
}));
ProgressThread.SetApartmentState(ApartmentState.STA);
ProgressThread.Start();
}
private void Close_Click(object sender, RoutedEventArgs e)
{
foreach(var ProgressThread in ProgressThreads)
{
if (ProgressThread.IsAlive == true)
{
ProgressThread.Abort();
}
}
}
}
You will need to keep a record of all threads you have opened when you click "Open". Then in your "Close" method loop over that list closing each one.
Member variable:
List<Thread> allThreads = new List<Thread>();
Then in your open handler add:
allThreads.Add(ProgressThread);
Then your close handler becomes:
foreach (Thread thread in allThreads)
{
if (thread.IsAlive)
{
thread.Abort();
}
}
That what you are trying is unorthodox should go without saying.

this is not waiting form, but completion notification of thread is required

private void btnSend_Click(object sender, RoutedEventArgs e)
{
Button obj=(Button)sender;
obj.Content="Cancel";
SendImage send = new SendImage();
Thread t = new Thread(send.Image);
t.Start();
//run separate thread.(very long, 9 hours)
//so dont wait.
//but the button should be reset to obj.Content="Send"
//Can I do this?
}
I want the button to be reset to "Send" (after completion of thread). But form should not wait. Is this possible?
You can do this more elegantly using the BackgroundWorker class.
XAML for the Button:
<Button x:Name="btnGo" Content="Send" Click="btnGo_Click"></Button>
Code :
private BackgroundWorker _worker;
public MainWindow()
{
InitializeComponent();
_worker = new BackgroundWorker();
_worker.WorkerSupportsCancellation = true;
_worker.WorkerReportsProgress = true;
}
private void btnGo_Click(object sender, RoutedEventArgs e)
{
_worker.RunWorkerCompleted += delegate(object completedSender, RunWorkerCompletedEventArgs completedArgs)
{
Dispatcher.BeginInvoke((Action)(() =>
{
btnGo.Content = "Send";
}));
};
_worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
Dispatcher.BeginInvoke((Action)(() =>
{
btnGo.Content = "Cancel";
}));
SendImage sendImage = args.Argument as SendImage;
if (sendImage == null) return;
var count = 0;
while (!_worker.CancellationPending)
{
Dispatcher.BeginInvoke((Action)(() =>
{
btnGo.Content = string.Format("Cancel {0} {1}", sendImage.Name, count);
}));
Thread.Sleep(100);
count++;
}
};
if (_worker.IsBusy)
{
_worker.CancelAsync();
}
else
{
_worker.RunWorkerAsync(new SendImage() { Name = "Test" });
}
}
Make the Button a member of your Window/UserControl class (by giving it a Name in XAML). When the thread eventually finishes, do this before returning from the thread method:
myButton.Dispatcher.BeginInvoke(
(Action)(() => myButton.Content = "Send"));

How to create and use WebBrowser in background thread?

How can I create System.Windows.Forms.WebBrowser in background STA thread? I try use some code like this:
var tr = new Thread(wbThread);
tr.SetApartmentState(ApartmentState.STA);
tr.Start();
private void wbThread()
{
CWebBrowser browser = new CWebBrowser();
var text = browser.Navigate("http://site.com", CWebBrowser.EventType.loadCompleted).Body.InnerHtml;
}
CWebBrowser - custom class, wich delegate System.Windows.Forms.WebBrowser object Navigate method and wait until page completed loads. The problem is LoadCompleted event on System.Windows.Forms.WebBrowser object never raises. I found some solution here, but it does not work (can't find method Application.Run() on my WPF app).
public class CWebBrowser : ContentControl
{
public readonly System.Windows.Forms.WebBrowser innerWebBrowser;
private readonly AutoResetEvent loadCompletedEvent;
private readonly AutoResetEvent navigatedEvent;
public enum EventType
{
navigated, loadCompleted
}
public CWebBrowser()
{
innerWebBrowser = new System.Windows.Forms.WebBrowser();
loadCompletedEvent = new AutoResetEvent(false);
navigatedEvent = new AutoResetEvent(false);
System.Windows.Forms.Integration.WindowsFormsHost host = new System.Windows.Forms.Integration.WindowsFormsHost();
host.Child = innerWebBrowser;
Content = host;
innerWebBrowser.DocumentCompleted +=new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(innerWebBrowser_DocumentCompleted);
innerWebBrowser.Navigated += new System.Windows.Forms.WebBrowserNavigatedEventHandler(innerWebBrowser_Navigated);
}
void innerWebBrowser_Navigated(object sender, System.Windows.Forms.WebBrowserNavigatedEventArgs e)
{
navigatedEvent.Set();
}
void innerWebBrowser_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
if (((sender as System.Windows.Forms.WebBrowser).ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete) || innerWebBrowser.IsBusy)
return;
var doc = innerWebBrowser.Document;
loadCompletedEvent.Set();
}
public System.Windows.Forms.HtmlDocument Navigate(string url, EventType etype)
{
if (etype == EventType.loadCompleted)
loadCompletedEvent.Reset();
else if (etype == EventType.navigated)
navigatedEvent.Reset();
innerWebBrowser.Navigate(url);
if (etype == EventType.loadCompleted)
loadCompletedEvent.WaitOne();
else if (etype == EventType.navigated)
navigatedEvent.WaitOne();
System.Windows.Forms.HtmlDocument doc = null;
Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(
delegate
{
doc = innerWebBrowser.Document;
}));
return doc;
}
}
Thansk for all advices and sorry for my bad english :o(
Why don't you use the default WebBrowser control like this?
public MainPage()
{
InitializeComponent();
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(startNavigate);
}
void startNavigate()
{
WebBrowser wb = new WebBrowser();
wb.LoadCompleted += new LoadCompletedEventHandler(wb_LoadCompleted);
wb.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(wb_Navigated);
wb.Navigate(new Uri("http://www.google.com"));
}
void wb_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
// e.Content
}
void wb_LoadCompleted(object sender, NavigationEventArgs e)
{
// e.Content when the document finished loading.
}
Edit: You are using old System.Windows.Forms.WebBrowser control, instead System.Windows.Controls.WebBrowser which is part of WPF.

Resources