Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

selenium - Access window object / browser scope from protractor

I'm running tests with protractor, but it seems impossible to access the JS 'window' object. I even tried adding a tag in my html file that would contain something like

var a = window.location;

and then try expect(a) but I couldn't make it work, I always get undefined references...

How should I process to access variables that are in the browser scope ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming you are using a recent version of Protractor, let's say >= 1.1.0, hopefully >= 1.3.1

Attempting to access Browser side JS code directly from Protractor won't work because Protractor runs in NodeJS and every Browser side code is executed through Selenium JsonWireProtocol.

Without further detail, a working example:

browser.get('https://angularjs.org/');

One-liner promise that, as of today, resolves to '1.3.0-rc.3'

browser.executeScript('return window.angular.version.full;');

You can use it directly in an expect statement given Protractor's expect resolves promises for you:

expect(browser.executeScript('return window.angular.version.full;')).
  toEqual('1.3.0-rc.3');

Longer example passing a function instead of a string plus without expect resolving the promise for you. i.e. for more control and for doing some fancy thing with the result.

browser.driver.executeScript(function() {
    return window.angular.version.full;
}).then(function(result) {
    console.log('NodeJS-side console log result: ' + result);
    //=> NodeJS-side console log result: 1.3.0-rc.3
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...