How to inject Javascript in WebBrowser control?

前端 未结 15 2526
夕颜
夕颜 2020-11-22 04:56

I\'ve tried this:

string newScript = textBox1.Text;
HtmlElement head = browserCtrl.Document.GetElementsByTagName(\"head\")[0];
HtmlElement scriptEl = browser         


        
15条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 05:31

    As a follow-up to the accepted answer, this is a minimal definition of the IHTMLScriptElement interface which does not require to include additional type libraries:

    [ComImport, ComVisible(true), Guid(@"3050f28b-98b5-11cf-bb82-00aa00bdce0b")]
    [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
    [TypeLibType(TypeLibTypeFlags.FDispatchable)]
    public interface IHTMLScriptElement
    {
        [DispId(1006)]
        string text { set; [return: MarshalAs(UnmanagedType.BStr)] get; }
    }
    

    So a full code inside a WebBrowser control derived class would look like:

    protected override void OnDocumentCompleted(
        WebBrowserDocumentCompletedEventArgs e)
    {
        base.OnDocumentCompleted(e);
    
        // Disable text selection.
        var doc = Document;
        if (doc != null)
        {
            var heads = doc.GetElementsByTagName(@"head");
            if (heads.Count > 0)
            {
                var scriptEl = doc.CreateElement(@"script");
                if (scriptEl != null)
                {
                    var element = (IHTMLScriptElement)scriptEl.DomElement;
                    element.text =
                        @"function disableSelection()
                        { 
                            document.body.onselectstart=function(){ return false; }; 
                            document.body.ondragstart=function() { return false; };
                        }";
                    heads[0].AppendChild(scriptEl);
                    doc.InvokeScript(@"disableSelection");
                }
            }
        }
    }
    

提交回复
热议问题