This sample code demonstrates how to inject a JavaScript file before any JavaScript code is executed on the web page. As you can see, the JavaScript file is added in the scope of ScriptContextCreated.


browserView.Browser.ScriptContextCreated += (sender, e) =>
{
    e.Browser.ExecuteJavaScript(
      @"var jsFile = document.createElement('script');
        jsFile.src = 'File';
        if (document.getElementsByTagName('HEAD').length == 0)
        {
            var observer = new MutationObserver(function(mutations)
            {
                for (var i = 0; i < mutations.length; i++)
                {
                    for (var j = 0; j < mutations[i].addedNodes.length; j++)
                    {
                        if (mutations[i].addedNodes[j].tagName == 'HEAD')
                        {
                            mutations[i].addedNodes[j].appendChild(jsFile);
                            observer.disconnect();
                        }
                    }
                }
            });

            observer.observe(document, 
            {
                childList:
                true,
                subtree:
                true
            });
        }
        else
        {
            document.head.appendChild(jsFile);
        }");
};



The check of the HEAD node existence was done to determine the case when it was not created yet. In this case, we create a MutationObserver that will receive events when the document is modified. If the HEAD node already exists at the moment when we are trying to inject the file, there is no need to create an observer, and we simply create and append a child node via JavaScript.