Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am using the method executeScript in selenium web driver, I found a problem:

js.executeScript("var b='1'; ");
js.executeScript("alert(b)");

After I run above code, I suppose get a alert window with value is 1, but it says:

b is not defined

My question is: I defined b as a global variable, but why I cannot get it in later?

share|improve this question

1 Answer

up vote 3 down vote accepted

Defining a variable as

var b='1'

limits the scope to the execution of the script. Selenium wraps the execution of javascript snippets into their own script so your variable does not survive the end of the script. Try

window.b = '1';

and then later

alert(window.b);

to put the variable into global scope.

share|improve this answer
Thanks. I also have another problem – Ryan Dec 13 '12 at 14:42
@user1849264 Just ask a new question. And please, if you're satisfied with my answer then accept it. – Valentin Dec 13 '12 at 14:47
Thanks, @Valentin . I also have another problem, I overwrite console.log function and put it into executeScript(), for example,'js.executeScript("console.log = function(txt) {alert('ok');};");', but it failed and exceptions are thrown on this code. I am thinking that if I can overwrite function in executeScript(). – Ryan Dec 13 '12 at 15:00
This has been done, one more confuse: stackoverflow.com/questions/13863355/… – Ryan Dec 14 '12 at 3:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.