Search code examples
c#javascriptwpfyoutube-apiawesomium

Capturing JavaScript Events in C# from YouTube API Using Awesomium


Am I able to capture a JavaScript event, in C#, when generated as a result of the YouTube API while running in Awesomium?

I have the following HTML which I load into my Awesomium browser:

<body>
    <div id="player"></div>

    <script src="http://www.youtube.com/player_api"></script>
    <script>
        var player;

        function onYouTubePlayerAPIReady() {
            player = new YT.Player('player', {
                height: '390',
                width: '640',
                videoId: '0Bmhjf0rKe8',
                events: {
                    'onReady': onPlayerReady,
                    'onStateChange': onPlayerStateChange
                }
            });
        }

        function onPlayerReady(event) {
            event.target.playVideo();
        }

        function onPlayerStateChange(event) {
            if (event.data == 0) {
                alert('done');
            }
        }
    </script>
</body>

How can I capture the onPlayerStateChange (or another event generated by it) back in the C#, so that my application can react when the video ends?


Solution

  • Provided you're using Awesomium.NET 1.7 RC, here are the steps to do it:

    • Create a global JavaScript object. See: CreateGlobalJavascriptObject
    • Add a custom method to the global JS object, and bind to it. See: JSObject.Bind
    • Call the custom method from inside your onPlayerStateChange handler:

      function onPlayerStateChange(event) {
          if (event.data == 0) {
              myGlobalObject.onPlayerStateChange();
          }
      }
      

    (The example assumes you created a global JS object named myGlobalObject and you added a onPlayerStateChange custom method to it.)

    This will fire the JavascriptMethodEventHandler you defined at JSObject.Bind.