Wednesday, 30 November 2011

Building an IE Add-On - Part 3

So far in our effort to create an Internet Explorer add-on, we've successfully ran a proof-of-concept and then refactored a little to add some site-specific logic.  This time we'll take another small step along and push that logic into an interface and set the stage for some more complicated behaviours.

Since we already have an appropriate method from last time, we just need to define our interface and our first implementation:

    interface ICssRepository {
        string GetCssText(string url);
    }

    class HardcodedCssRepository : ICssRepository {
        public string GetCssText(string url) {
            var uri = new Uri(url);
            switch (uri.Host.ToLowerInvariant()) {
                case "www.bing.com":
                    return "a{ color:red !important; }";
                case "www.google.co.uk":
                    return "a{ color:purple !important; }";
            }
            return null;
        }
    }


With those in place we can start to wire it up, first adding a reference which for now is set by the constructor...

        private readonly ICssRepository _cssRepository;
        public BHO() {
           
_cssRepository = new HardcodedCssRepository();
        }

... and then updating our event handler to call into our new interface instead, slightly cleaning the code by casting the event parameters to something useful ...

        void _webBrowser2Events_DocumentComplete(object pDisp, ref object URL) {
            if (pDisp is IWebBrowser2 && URL is string)
                OnDocumentCompleted((IWebBrowser2)pDisp, (string)URL);
        }
        void OnDocumentCompleted(IWebBrowser2 webBrowser2, string url) {
            //grab the css text for the document url
            var cssText =
_cssRepository.GetCssText(url);
            if (cssText == null) return;

            //add the css text
            HTMLDocument document = webBrowser2.Document;
            var css = document.createStyleSheet("", 0);
            css.cssText = cssText;
        }

Next up, we'll move away from hardcoded styles and experiment with an alternative storage format...

0 comments:

Post a Comment