## Javascript to .Net

Asynchronous events from the Javascript environment.

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

- Create a class with a public method that will be exposed to the Javascript environment (see CefSharp\CefSharp.Example\ScriptedMethodsBoundObject.cs RaiseEvent().)
- Bind the class to the Javascript runtime using RegisterJsObject (see CefSharp\CefSharp.WinForms.Example\BrowserTabUserControl.cs ctor().)
- Invoke the exposed function in Javascript using window.[bound object name].[method name] (see CefSharp\CefSharp.Example\ScriptedMethods.cs ListenForClick().)

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.

- Create Javascript code that monitors the web page and invokes the exposed function (see CefSharp\CefSharp.Example\ScriptedMethods.cs ListenForClick().)

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}.`);
                })();