Access .NET objects from JavaScript

4,640 views
Skip to first unread message

Remo Laubacher

unread,
May 19, 2012, 3:28:09 AM5/19/12
to cefs...@googlegroups.com
I've seen about this topic  https://groups.google.com/forum/#!topic/cefsharp/1u0AOOuIzF8 

But what about the other way round? Can I create an object in .NET and access its properties from my JavaScript code, embedded in the browser?

Thanks!

Jack O'Connor

unread,
May 19, 2012, 4:08:23 AM5/19/12
to remo.la...@gmail.com, cefs...@googlegroups.com
Yep, this is actually really easy:


CEF.RegisterJsObject() takes two parameters, a name and an object, and exposes the object to all windows using that name in the global scope. This is similar to the ObjectForScripting interface provided by the builtin (IE) WebBrowser control in WinForms. Some differences that I think still apply:
- The IE version lets you use "object" type parameters on the native methods to accept arbitrary values from JS (including things like functions, this boggles my mind), but the CEF version is more strictly typed. I think you can pass out JS objects as Dictionaries, but I tend to find it safer and more convenient to just stick to strings. Unlike regular JS functions, these native functions will throw if you give the wrong type/number of args.
- The IE version exposed properties as well as functions, but I think in CEF only the functions on the object are wrapped, so if you wanted to expose public members or properties, you might need to use plain old get/set methods instead.

By the way, if you want to go the other way and call JS functions from C#, you can do that with the ExecuteScript/EvaluateScript methods.


Those just take strings containing arbitrary JS, and execute them in the window. The evaluate ones do this synchronously, and return the result. To safely concatenate arguments into a string like that, especially string arguments, I like to use JSON encoding to create a JS literal.  Json.NET is a great library for that, if you're using a version of .NET that doesn't include JavaScriptSerializer.

--
You received this message because you are subscribed to the Google Groups "CefSharp" group.
To view this discussion on the web visit https://groups.google.com/d/msg/cefsharp/-/_0bd2UVup8QJ.
To post to this group, send email to cefs...@googlegroups.com.
To unsubscribe from this group, send email to cefsharp+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/cefsharp?hl=en.

Remo Laubacher

unread,
May 19, 2012, 4:35:11 AM5/19/12
to cefs...@googlegroups.com, remo.la...@gmail.com
Jack, thanks a lot of the quick & detailed answer.

Now that I have the right keyword, I also found an example:

Jack O'Connor

unread,
Jun 5, 2012, 9:58:44 PM6/5/12
to remo.la...@gmail.com, cefs...@googlegroups.com
Update: it is now possible to do local bindings as well, which are only visible from one browser window.

Reply all
Reply to author
Forward
0 new messages