title: How to send JavaScript code to IE using C# (.Net 3.5), run it, then get a string return value from the JS code?
body: <p>We are developing an application which needs to interact with the active document in IE.</p>
  
  <p><strong>Context:</strong> The app is a C#, .Net 3.5 desktop app. The goal is to highlight specific text elements in the web page on user request. For this we need to retrieve and interpret web page elements (the need for the return value) then act on them through another JS call. The operations that must be made in the web page are not all done at the same time so we must get some kind of "snapshot" of the interesting text elements (we do this on the Mac version of our app by returning a string containing an XML representation of those elements).</p>
  
  <p>In .Net we used <code>IHTMLDocument2</code>'s <code>execScript</code> method successfully to run some JavaScript inside the active IE document, but we can't seem to find a way to get a return value from the call. Based on the doc execScript returns an execution success/failure constant which is not what we need.</p>
  
  <p>In essence what we need to do is to load some JavaScript from a text file into a string, then send it to IE for execution. Then we need to get a string back from the called script.</p>
  
  <p>Any hints on what objects to use? How to proceed to get this functionality?</p>
  
  <p>Thanks in advance!</p>
  
  <p><strong>My colleague found the solution, based on what Alun Harford said:</strong></p>
  
  <pre><code>string jsToRun = "function myTest() { return document.title; } myTest();";
  mshtml.IHTMLDocument2 myIHTMLDocument2 = GetSelectedIEWindow();
  IE ie = IE.AttachToIE(Find.ByUrl(myIHTMLDocument2.url));
  string jsReturn = ie.Eval(jsToRun);
  </code></pre>
  
  <p><code>jsReturn</code> then contains the string value returned from <code>myTest()</code> in JavaScript. Note that there is no <code>return</code> before the <code>myTest()</code> function call in the script!</p>