Asynchronous events from the Javascript environment.

Sending events from the Javascript environment to a .Net class involves the following:

Most of the time the web page's Javascript will be written specifically to interact with the embedded browser and any class methods that are exposed through RegisterJsObject. However to monitor some web pages it may be necessary to inject Javascript code that can detect changes and events in the web page and then invoke a method on a bound object.

Demonstration

This page demonstrates the injection of Javascript code that asynchronously invokes a bound method when a button is clicked. Clicking the Script -> Listen for button click menu will cause Javascript1 to be executed that adds an event listener to the click event of the button below. When the button is clicked the bound class's exposed method will be invoked with information from the event including the element's id attribute and tag name.

1Javascript code that adds a click event listener and passes event data to .Net when the event occurs.

            (async function ()
            {
                await CefSharp.BindObjectAsync("boundEvent");
                var counter = 0;
                var elem = document.getElementById('test-button');
                elem.removeAttribute('disabled');
                elem.addEventListener('click', function(e)
                {
                    if (!window.boundEvent){
                        console.log('window.boundEvent does not exist.');
                        return;
                    }
                    counter++;
                    window.boundEvent.raiseEvent('click', {count: counter, id: e.target.id, tagName: e.target.tagName});
                });
                console.log(`Added click listener to ${elem.id}.`);
            })();