Access window object / browser scope from protractor

17,952

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
});
Share:
17,952

Related videos on Youtube

hilnius
Author by

hilnius

Updated on June 15, 2022

Comments

  • hilnius
    hilnius about 2 years

    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 ?

  • hilnius
    hilnius over 9 years
    Actually with the protractor version I'm using, I had to use browser.executeScript('return myvar;').then(function(myvar) { ... }); but worked perfectly, thanks!
  • chrismarx
    chrismarx about 9 years
    if i return just the window object using this method, i get "Maximum call stack size exceeded" :(
  • Leo Gallucci
    Leo Gallucci about 9 years
    Is probably a bad idea anyway @chrismarx, return only what you really need ;)
  • Yaroslav Basovskyy
    Yaroslav Basovskyy over 5 years
    @LeoGallucci, what can you suggest if I need to get window variable which is not exist at this time? For example window.angular.version.full; but version will be populated some time in the future.
  • Leo Gallucci
    Leo Gallucci over 5 years
    sorry idk, it's been years since I used Protractor