Search code examples
javascriptc#cefsharpchromium-embedded

CefSharp - JavascriptObjectRepository with multipages


I have problems to understand my error with ChromiumWebBrowser.JavascriptObjectRepository

I can register my C# object with this method:

chromiumWebBrowser.JavascriptObjectRepository.Register("gui", myObjectIndex, true);
chromiumWebBrowser.Address = "index.html";

And the javascript code works correctly on my first page index.html:

$("mybutton").on("click", function (event) {
    event.preventDefault();
    gui.onClickButtonChangePage();  // calls MyObjectIndex.OnClickButtonChangePage()
});

However when the page change, i want to change my object myObjectIndex to MyObjectPage2.

I'm trying to do it:

chromiumWebBrowser.JavascriptObjectRepository.UnRegister("gui");
chromiumWebBrowser.JavascriptObjectRepository.Register("gui", myObjectPage2, true);
chromiumWebBrowser.Address = "page2.html";

And when I press the buttons on page2.html:

    1. Get error
$("mybutton2").on("click", function (event) {
 event.preventDefault();
 gui.onClickButton2();  // didn't call MyObjectPage2.OnClickButton2() !
});
    1. Do nothing:
$("mybutton2").on("click", function (event) {
    event.preventDefault();
    (async () =>
    {
        await CefSharp.BindObjectAsync("gui", "gui");
        gui.onClickButton2(); // Nothing happens
    })();
});

wiki CefSharp


Solution

  • I just needed to call this code:

    $(document).ready(function () {
            CefSharp.DeleteBoundObject("gui");
            CefSharp.RemoveObjectFromCache("gui");
            CefSharp.BindObjectAsync("gui");
    });