Note that there are some explanatory texts on larger screens.

plurals
  1. POTrying to set/get a JavaScript variable in an ActiveX WebBrowser from C#
    text
    copied!<p>We have a windows application that contains an ActiveX WebBrowser control. As part of the regular operation of this application modifications are made to the pages that are displayed by the ActiveX WebBrowser control. Part of these modifications involve setting a JavaScript variable in a web page being loaded into the ActiveX WebBrowser. </p> <p>We need to initialize this variable within C# (originally, VB6 code was initializing the value). The value of this variable is a COM-visible class object. </p> <p>However, for simplicity we've reduced the problem to setting a string value. Our original page involves frames and the like but the same problems happens in a page like this:</p> <pre><code>&lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;Test&lt;/TITLE&gt; &lt;SCRIPT type="text/javascript"&gt; var field = 'hello world'; &lt;/SCRIPT&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;input type="button" value="See field" onclick="javascript:alert(field);"/&gt; &lt;/BODY&gt; &lt;/HTML&gt; </code></pre> <p>We want to access the <em>field</em> variable and assign a value to it. In VB6 the code for this was pretty straightforward:</p> <pre><code>doc.Script.field = 'newValue' </code></pre> <p>However, in C# we've had to resort to other tricks, like this: </p> <pre><code>Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSet(Script, null, "field",new object[] { "newValue"},null, null); </code></pre> <p>The point of the page is to test whether our variable was properly assigned by C#. Clicking on the button should yield whatever new value was injected by C#. So for example, clicking on the button in the page we get an alert showing: "newValue".</p> <p>That works the first time, but it doesn't work if we reload the page. On subsequent calls we cannot set the value of the variable <code>field</code>. </p> <p>Has anyone had any experience doing this type of operation before?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload