Internet Explorer Extensions

2019-04-16 04:35发布

I created an IE extension from this source: How to get started with developing Internet Explorer extensions? And it work great. But i want to change

int IOleCommandTarget.Exec(IntPtr pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
    {
        var form = new HighlighterOptionsForm();
        form.InputText = TextToHighlight;
        if (form.ShowDialog() != DialogResult.Cancel)
        {
            TextToHighlight = form.InputText;
            SaveOptions();
        }
        return 0;
    }

to this:

int IOleCommandTarget.Exec(IntPtr pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
    {
        HTMLDocument document = (HTMLDocument)browser.Document;

        IHTMLElement head = (IHTMLElement)((IHTMLElementCollection)
                               document.all.tags("head")).item(null, 0);
        IHTMLScriptElement scriptObject =
          (IHTMLScriptElement)document.createElement("script");
        scriptObject.type = @"text/javascript";
        var text = @"alert('hello') ";
        scriptObject.text = "(function(){" + text + "})()";
        ((HTMLHeadElement)head).appendChild((IHTMLDOMNode)scriptObject);
        return 0;
    }

But when i build it, and click on the button. I doesn't give me an alert message. I want just only inject a script. Any idea or trick... to fix this problem

1条回答
三岁会撩人
2楼-- · 2019-04-16 05:09

It is not working because script tags added to the document are not evaluated automatically.

You must eval the script manually, like the following:

var document = browser.Document as IHTMLDocument2;
var window = document.parentWindow;
window.execScript(@"(function(){ alert('hello') })()");

Also, you don't need to add the script tag at all... just execute the script using window.execScript.

查看更多
登录 后发表回答