Search code examples
wpfchromium-embeddedcefsharp

CEFSharp RegisterJsObject reference error


I know this question has been beaten to death with this library but despite the examples available, I'm having a hard time getting Javascript bindings to work with WPF.

I'm using CefSharp.Common 37.0.0 The Javascript error that I'm getting is: Uncaught ReferenceError: myClass is not defined

Below, you will find a small code example. I feel like this is fairly straight forward. Let me know if anybody needs additional information. Thanks.

Here is my HTML / JS logic

<html>
    <head>
        <script type="text/javascript">
            function test(){

                MyClass.myFunc();
            }
        </script>        
    </head>

    <body>
        This is a cat
        <button id='testBtn' onclick="test();" type="button">Meow</button>
    </body>
</html>

C# / .NET Logic

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace HTML5
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Loaded += MainWindow_Loaded;
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            webBrowser.Loaded += webBrowser_Loaded;
        }

        void webBrowser_Loaded(object sender, RoutedEventArgs e)
        {
            webBrowser.ShowDevTools();            
            webBrowser.RegisterJsObject("MyClass", new MyClass());            

        }
    }

    public class MyClass
    {
        public void MyFunc()
        {
            Console.WriteLine("");
        }
    }
}

--Edit Just noticed the LoadError event is fired every time with an Aborted status. This fires whether I'm using my local HTML file or hosting Google.com. Could this be part of the problem?


Solution

  • Need to Register objects directly after Browser is created as there's no on the fly binding as yet

    https://github.com/cefsharp/CefSharp/wiki/Frequently-asked-questions#3-how-do-you-expose-a-net-class-to-javascript

    At a guess your object is being registered too late. Try registering after InitializeComponent.

    For reference there is an open Feature Request for on the fly binding, see https://github.com/cefsharp/CefSharp/issues/602

    As for the Aborted error, I've seen that quite a bit with 37 even though pages load correctly. It appears to go away in version 39 (There are -pre releases available).