Search code examples
javascriptfunctiongistsynthetic

Calling functions from a Gist


I'm trying to call JS functions from a Gist to be used within a synthetic script.

JS Gist:

function FBTEST(){console.log("Test function working.");}
// Clicks
function FBXPC(XPATH){$browser.findElement($driver.By.xpath(XPATH)).click();}
function FBLTC(LINKTEXT){$browser.findElement($driver.By.linkText(LINKTEXT)).click();}
function FBIDC(ID){$browser.findElement($driver.By.id(ID)).click();}
function FBNMC(NAME){$browser.findElement($driver.By.name(NAME)).click();}
function FBCNC(CLASSNAME){$browser.findElement($driver.By.className(CLASSNAME)).click();}
// Send Keys
function FBXPSK(XPATH,SK){$browser.findElement($driver.By.xpath(XPATH)).sendKeys(SK);}
function FBLTSK(LINKTEXT,SK){$browser.findElement($driver.By.linkText(LINKTEXT)).sendKeys(SK);}
function FBIDSK(ID,SK){$browser.findElement($driver.By.id(ID)).sendKeys(SK);}
function FBNMSK(NAME,SK){$browser.findElement($driver.By.name(NAME)).sendKeys(SK);}
function FBCNSK(CLASSNAME,SK){$browser.findElement($driver.By.className(CLASSNAME)).sendKeys(SK);}
console.log("fbf_0.0.1 initialised.")

So far I can successfully run the Gist however I cant seem to call the functions from within the Gist.

Synthetic script calling the Gist.

var req = require('urllib-sync').request;
var res = req('https://gist.githubusercontent.com/robhalli/c03e4fe370da9528898d85a0718cf6b2/raw/3667377b02175008eb425e8966722113df87faac/fbf.js');
var monitorBody = new Function('$browser', res.data);

monitorBody();

I want to be able to call the functions from the Gist above.

For example:

$browser.FBTEST();

That should print 'Test function working.' in the console. However its currently not calling the function correctly.


Solution

  • You can use NodeJS vm package https://nodejs.org/api/vm.html

    const vm = require('vm');
    const $browser = { };
    vm.createContext($browser);
    
    const code = res.data;
    vm.runInContext(code, $browser);
    
    $browser.FBTEST();