1

When running the protractor script below

let resultantArr = [];

resultantArr = await browser.executeScript("var elements = document.querySelectorAll('ul[class=\'wbs-droplist-container\'][id*=\'droplist\'] li[class=\'wbs-droplist-item\'][id*=\'droplistitem\']') \
var arr = []; \
for (var i = 0; i < elements.length; i++) { \
  arr.push(elements[i].innerText); \
  } \
return arr;")

return resultantArr;

I'm getting Failed: javascript error: missing ) after argument list error. Please help me to solve this.

Poovin
  • 164
  • 3
  • 15
  • Try using ` as instructed: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/executeScript also whats up with \ signs? – ikiK Jul 15 '21 at 13:46
  • 1
    @ikiK The backslash `\ ` is a possiblity to continue the string in the next line without actually having a linebreak in the string. When you use the backticks `\`` to span a string over multiple lines, it will have a actual linebreak in it. – derpirscher Jul 15 '21 at 13:49
  • @derpirscher Interesting, thanks, news to me. – ikiK Jul 15 '21 at 13:57

2 Answers2

1

Try

return await browser.executeScript(`
  var elements = document.querySelectorAll("ul[class='wbs-droplist-container'][id*='droplist'] li[class='wbs-droplist-item'][id*='droplistitem']");
  var arr = [];
  for (var i = 0; i < elements.length; i++) {
    arr.push(elements[i].innerText);
  }
  return arr;
`)
Sergey Pleshakov
  • 7,964
  • 2
  • 17
  • 40
0

For creating a multiline string constant you should enclose your string in backticks and not use the backslash within the string. See below code snippet for the differences. s1 will contain no linebreak, but s2 will.

const s1 = "foo \
bar"

const s2 = `foo
bar`

console.log(s1);
console.log(s2);

Thus when applied to your code snippet, you are actually creating a script like the following

var script = "var elements = document.querySelectorAll('...') \
var arr = []; \
for (var i = 0; i < elements.length; i++) { \
  arr.push(elements[i].innerText); \
  } \
return arr;"

console.log(script);

which is invalid because you have something like the following in it (note the missing semicolon before the second var)

var elements = document.querySelector(...)   var arr = [];

whereas the following snippet produces a valid script

var script = `var elements = document.querySelectorAll('...')
var arr = [];
for (var i = 0; i < elements.length; i++) {
  arr.push(elements[i].innerText);
}
return arr;`

console.log(script);

because, when you have a linebreak before the next var you typically don't need a semicolon.

I'm not really sure, why you get an error about a missing ), maybe you have a different script which also fails?. Actually the error from that above script should be

Uncaught SyntaxError: Unexpected token 'var'

derpirscher
  • 14,418
  • 3
  • 18
  • 35