Protractor set global variables

You can also set global variables in onPrepare() using global:

onPrepare: function () {
    global.myVariable = "test";
},

Then, you would just use myVariable throughout the tests as is.

This is actually how protractor, browser and other built-in global variables were made available globally:

Runner.prototype.setupGlobals_ = function(browser_) {
  // Export protractor to the global namespace to be used in tests.
  global.protractor = protractor;
  global.browser = browser_;
  global.$ = browser_.$;
  global.$$ = browser_.$$;
  global.element = browser_.element;
  global.by = global.By = protractor.By;

  // ...
}

Note that with this approach you are polluting your global scope/namespace, be careful.


It is possible to set globals from the Protractor config file with the help of params property:

exports.config = {
    // ...

    params: {
        glob: 'test'
    }

    // ...
};

And you can access it in the specs using browser.params.glob.

See the reference config file.

The params object will be passed directly to the Protractor instance, and can be accessed from your test as browser.params. It is an arbitrary object and can contain anything you may need in your test. This can be changed via the command line as:

protractor conf.js --params.glob 'other test'

Update:

From the docs for browser.executeScript:

If the script is provided as a function object, that function will be converted to a string for injection into the target window. Any arguments provided in addition to the script will be included as script arguments and may be referenced using the arguments object.

So, JavaScript scope in this case does not work, you function that is passed to browser.executeScript won't have any closure variables from spec like browser. But you can pass these variables explicitly:

browser.executeScript(function (glob) {

    // use passed variables on the page
    console.log(glob);

}, browser.params.glob);