I have a WinForm application that using cefsharp web browser. From what I learnt about cefsharp, the events MouseDown, Click cannot trigger in WinForm. So I decided to use javascript to send a message to the console, and trigger ChromiumWebBrowser.ConsoleMessage event instead. But that did not work well. Did I mess up the javascript code or execute the code wrongly?
Here are the codes, please noted that UI.cs is a Form object. A panel object pn_Browser already created in the design view. What I tried to do is, click any element and send "success" to the console. Then the Background show the received message if the message in console.log is "success".
Background.cs
public ChromiumWebBrowser browser;
public Background()
{
browser = new ChromiumWebBrowser("https://www.google.com");
browser.ConsoleMessage += browser_ConsoleMessage;
browser.FrameLoadEnd += browser_FrameLoadEnd;
}
public void browser_ConsoleMessage(object sender, ConsoleMessageEventArgs e)
{
if (e.Message == "success")
{
System.Windows.Forms.MessageBox.Show("Received message.");
}
}
public void browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{
Chromium.ExecuteScriptAsync("document.addEventListener(\"click\", function() {alert('Detect a click.');});");
}
UI.cs
public UI()
{
InitializeComponent();
Background background = new Background();
pn_Browser.Controls.Add(background.browser);
background.browser.JavascriptMessageReceived += browser_JavascriptMessageReceived;
background.browser.ExecuteScriptAsyncWhenPageLoaded(
"function test() {console.log(\"success\")}" +
"document.addEventListener(\"click\", test);"
);
}
delegate void JavascriptReceivedCallback(object sender, JavascriptMessageReceivedEventArgs e);
private void browser_JavascriptMessageReceived(object sender, JavascriptMessageReceivedEventArgs e)
{
if (InvokeRequired)
{
JavascriptReceivedCallback callback = new JavascriptReceivedCallback(Browser_JavascriptMessageReceived);
Invoke(callback, new object[] { sender, e };
}
else
{
MessageBox.Show(e.Message.ToString());
}
}
Related
OK so this works on Android... I'm stuck on iOS.
I have a custom HTML WebView which has a JavaScript event:
const string html= #"<button type=""button"" onClick=CSharp.SendButton(' + buttonCode + ')"">Click here</button>";
On Android, I have a webview custom renderer:
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (Control != null)
{
Control.Settings.JavaScriptEnabled = true;
Control.AddJavascriptInterface(new JSBridge(Forms.Context), "CSharp");
}
base.OnElementPropertyChanged(sender, e);
}
And JSBridge is a bridge between Javascript and C#:
public class JSBridge : Java.Lang.Object
{
Context context;
public JSBridge(Context context)
{
this.context = context;
}
[Export]
[JavascriptInterface]
public void SendButton(string code)
{
// I can pass the buttonCode here
}
}
How can I do something similar on iOS?
Please note: I am aware of the HybridWebView examples on the Microsoft website: I dont want to use a seperate Javascript file, I want to fire the event from my HTML and catch it in my renderer.
I'm trying to fire an OnServerClick event from some anchor tag created dynamically. My event isn't firing from my anchor tag. i have no error.
Can someone help me ?
HtmlAnchor btn_close = new HtmlAnchor();
btn_close.Attributes.Add("class", "close");
btn_close.Attributes.Add("data-dismiss", "alert");
btn_close.Attributes.Add("aria-label", "Ne plus afficher");
btn_close.Attributes.Add("title", "Ne plus afficher");
btn_close.Attributes.Add("runat", "server");
btn_close.ServerClick += new EventHandler(hideNotificationBtn_Click);
btn_close.ID = notificationSent.NotificationSentID.ToString();
btn_close.InnerText = "test";
div_alert.Controls.Add(btn_close);
protected void hideNotificationBtn_Click(object sender, EventArgs e)
{
HtmlAnchor cb = (HtmlAnchor)sender;
int test = int.Parse(cb.Name);
NotificationSent.SetNotificationAsHidden(int.Parse(cb.Name));
}
My hide notification isn't fired from by anchor when i click on it.
I already tried to change it to a button.
Thank you for your help.
Anchors don't call server side functions even when they are runat server, however there is the LinkButton class that can be used instead. Ultimately it is rendered as JavaScript initiated postback. Check out https://forums.asp.net/p/1519048/3644158.aspx for more information.
Make sure you are creating that button early enough in the page lifecycle. Look to get it created OnInit of the Page.
This is because the event handling events happen after Page Init. Of course, the button has to have been created before the events can be detected on
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["falg"] != null)
{
Create();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Create();
ViewState.Add("falg", true);
}
void BtnServices_Click(object sender, EventArgs e)
{
Response.Write("hi");
}
void BtnServices_Command(object sender, CommandEventArgs e)
{
Response.Write("hi");
}
void Create()
{
BtnServices = new Button();
BtnServices.ID = "BtnServices";
BtnServices.Text = "Click Me";
BtnServices.Click += new EventHandler(BtnServices_Click);
BtnServices.Command += new CommandEventHandler(BtnServices_Command);
form1.Controls.Add(BtnServices);
}
Easier and reliable way to do this could be , instead of dynamically
adding the control, always add it, but set Visible=false initially.
Then where you're currently adding it, instead just make it visible.
I use GeckoWebBrowser component for get some webpages. But I don't know when page JavaScripts fully completed.
For detecting page full load I use event DocumentCompleted.
private GeckoWebBrowser wb = new GeckoWebBrowser();
private bool doc_loaded = false;
wb.DocumentCompleted += Browser_DocumentCompleted;
doc_loaded = false;
wb.Navigate(url);
Wait_Load();
private void Browser_DocumentCompleted(object sender, EventArgs e)
{
doc_loaded = true;
}
private void Wait_Load()
{
while (doc_loaded == false)
{
Application.DoEvents();
Application.RaiseIdle(new EventArgs());
}
}
How detect that all JavaScripts completed in GeckoWebBrowser?
Neither of the Javascript function is executed in "btnrepeat()", although I have called another javascript in page_load event and that is working fine
C#
protected void Button1_Click(object sender, EventArgs e)
{
Timer1.Enabled = true;
workerThread = new Thread(new ThreadStart(btnrepeat));
workerThread.Start();
}
protected void btnrepeat()
{
ClientScript.RegisterClientScriptBlock(GetType(), "mys", "abcd()", true);
for (int i = 1; i <= filecount; i++)
{
string trnsfrpth = #"E:\\ProjectLocalPath\" + filename;
last_file++;
balance_load(filename, trnsfrpth);
Thread.Sleep(200);
}
ClientScript.RegisterClientScriptBlock(GetType(), "mytts", "abcd()", true);
//Label1.InnerHtml = last_file.ToString();
//This is not aspx label, but an HTML div
//this is possible actually but not working here
}
Javascript
function abcd() {
alert('hello');
}
Function is doing what it is supposed to, so there is no logical mistake.
And I've also tried,
ClientScript.RegisterStartupScript(GetType(), "mytts", "abcd()", true);
And The last 3 lines commented is another problem, it doesn't work...why ?
I am attaching an onClick event to the Add Record button on my RadGrid. Code as follows:
Code Behind
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
if (e.Item is GridCommandItem)
{
LinkButton lnk = (LinkButton)e.Item.FindControl("InitInsertButton");
lnk.Attributes.Add("onClick", "testClick()");
}
}
Javascript
function testClick(){
// Perform some Client Side Validation
var validated = false;
if(!validated){
radalert('Validation Fail', 100, 100, 'Window', null, null);
// What to call here to prevent the RadGrid from going into Insert (Edit) mode??
//I tried return false; but that did not prevent the grid.
}
}
So on my JS call, after the alert window has been displayed and I closed it, the RadGrid still goes into edit mode.
I tried a variation of the following:
Code Behind
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
if(e.CommandName == RadGrid.InitInsertCommandName)
{
// If Validation Failed, prevent Radgrid from going to Edit Mode.
RadGrid1..MasterTableView.ClearEditItems();
}
}
Posting an answer so that for everyone who may stumble on this:
Code Behind:
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
if (e.Item is GridCommandItem)
{
LinkButton lnk = (LinkButton)e.Item.FindControl("InitInsertButton");
lnk.Attributes.Add("onClick", "return testClick()");
}
}
Javascript
function testClick(){
// Perform some Client Side Validation
var validated = false;
if(!validated){
radalert('Validation Fail', 100, 100, 'Window', null, null);
return false;
}
}