How can you insert a Javascript function into the page and then execute it?

3,604 views
Skip to first unread message

Chris Hansen

unread,
Aug 23, 2015, 12:09:09 AM8/23/15
to CefSharp

I just started using CefSharp today and I was able to do this with the default Windows Forms web browser but I can't use that for what I need to do and here is what that looked like:
            HtmlElement head = browser.Document.GetElementsByTagName("head")[0];
            HtmlElement scriptEl = browser.Document.CreateElement("script");
            IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
            element.text = "function enterJackpot() { $('#submit-wager').trigger('click'); }";
            head.AppendChild(scriptEl);
            browser.Document.InvokeScript("enterJackpot");

But this was in the regular Windows Forms browser, is there a way to do this exact same thing with CefSharp?

Alex Maitland

unread,
Aug 23, 2015, 4:04:01 AM8/23/15
to Chris Hansen, CefSharp

https://github.com/cefsharp/CefSharp/wiki/Frequently-asked-questions#1-how-do-you-call-a-javascript-methods-from-net

 

No need to declare a script block, once the browser has loaded you can execute a string of javascript. Obviously you can execute code directly or declare functions/classes.

 

Sent from Mail for Windows 10

--
You received this message because you are subscribed to the Google Groups "CefSharp" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cefsharp+u...@googlegroups.com.
To post to this group, send email to cefs...@googlegroups.com.
Visit this group at http://groups.google.com/group/cefsharp.
For more options, visit https://groups.google.com/d/optout.

 

 

Chris Hansen

unread,
Aug 23, 2015, 12:20:12 PM8/23/15
to CefSharp, chris...@gmail.com
Thanks for the reply, but I'm not sure if I did it right. Would it just be something like this then?
browser.ExecuteScriptAsync("$('#submit-wager').trigger('click')");

This didn't work for me.

Alex Maitland

unread,
Aug 23, 2015, 4:05:44 PM8/23/15
to CefSharp, chris...@gmail.com
That looks fine. Are you waiting for the browser to finish loading?

https://github.com/cefsharp/CefSharp/blob/cefsharp/41/CefSharp/IWebBrowser.cs#L48

Check `IsLoading` property of the event args

Chris Hansen

unread,
Aug 23, 2015, 4:28:57 PM8/23/15
to CefSharp
Yes, the page is finished loading when I call it. It's just on a button click.

Chris Hansen

unread,
Aug 23, 2015, 5:47:37 PM8/23/15
to CefSharp
Thanks for the replies everyone but I figured it out. I tried a similar thing on a different site and it works there. The website I was using must have some sort of protection against this.

Alex Maitland

unread,
Aug 23, 2015, 7:28:08 PM8/23/15
to CefSharp
Incase your not aware, you can use the Chromium DevTools to debug javascript.

https://github.com/cefsharp/CefSharp/blob/cefsharp/41/CefSharp/IWebBrowser.cs#L304
Reply all
Reply to author
Forward
0 new messages