Eval with WatiN

time to read 10 min | 1962 words

I just run into a situation where, for the tests, I need to run a script in IE, and get result back for the test. The problem is that IE doesn't expose anything like the eval() command in javascript. It does, however, exposes an execScript() command, but this has no return value. A bit of thinking produced this code:

protected string Eval(string code)

{

       string elementId = Guid.NewGuid().ToString();

       string create =string.Format(@"

var elem = document.createElement('INPUT');

elem.id = '{0}';

elem.type = 'HIDDEN';

elem.value = {1};

document.body.appendChild(elem);

",elementId, code);

       RunScript(create);

       string result = ie.TextField(elementId).Value;

 

       string remove = string.Format(@"

var elem = document.getElementById('{0}');

document.body.removeChild(elem);

", elementId);

       RunScript(remove);

       return result;

}

 

protected void RunScript(string js)

{

       IHTMLWindow2 window = ((HTMLDocument) ie.HtmlDocument).parentWindow;

       window.execScript(js, "javascript");

}

The isn't very pretty code, but it works. We create a new hidden input field element, set its value to whatever the code that we were given is doing, getting the value of the field, and then remove it. Simple when I see it now, but it was fairly hard to figure out.