1

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

Community
  • 1
  • 1
user1731468
  • 864
  • 2
  • 9
  • 30

1 Answers1

0

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.

Miguel Angelo
  • 23,796
  • 16
  • 59
  • 82
  • Document must be cast to `IHTMLDocument2`, so that you have access to the `execScript` method... if it still does not work, please post the exact error message. – Miguel Angelo Nov 25 '12 at 21:25
  • now, it doesn't show an error for Build. I open IE and click on that button. nothing show up. – user1731468 Nov 25 '12 at 21:39
  • Hi, I have edited my other answer (on [Developing Internet Explorer Extensions?](http://stackoverflow.com/questions/5643819/developing-internet-explorer-extensions)), so that now you are allowed to access the `browser` object within the `Exec` method... that is what was wrong! Take a look: http://stackoverflow.com/a/5740004/195417 – Miguel Angelo Nov 26 '12 at 03:35
  • any idea how how i can do this also for inject a CSS style code – user1731468 Nov 29 '12 at 13:33
  • Everything you can do with javascript, you can also do with C#... the objects are the same. Take a look at this: [How to create a – Miguel Angelo Nov 29 '12 at 16:12