问题
Trying to execute a javaScript command using the built in Selenium EventFiringWebDriver class.
EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(driver);
eventFiringWebDriver.executeScript("document.querySelector('[ng-reflect-title='Assessment']>div.cc-tile>div.cc-tile-body').scrollTop=370");
But this yields the error: Runtime.evaluate threw exception: SyntaxError: missing ) after argument list
if I use a the long ccs selector that Chrome gives me for this object of:
body > bb-root > best-app > div > div.cc-content > bb-best > bb-assess > best-tile > div > div
in place of:
[ng-reflect-title='Assessment']>div.cc-tile>div.cc-tile-body
Then it works perfectly.
Both of the above ccs selectors yield a single object on the page when run through the Chrome Dev Tools. I would prefer to use the more dynamic selector.
回答1:
Here's the JavaScript you are trying to run. With the help of Stack Overflow's code highlighting, can you see the problem?
document.querySelector('[ng-reflect-title='Assessment']>div.cc-tile>div.cc-tile-body').scrollTop=370
Note the colouring of the word Assessment
.
You've tried to put a string literal inside another string literal but you haven't escaped quotes so the JavaScript compiler thinks the string literal ends just before Assessment
. You will either need to use double-quotes instead of single quotes for one pair of quotes, or escape the inner quotes.
Complicating matters further is the fact that this JavaScript fragment which contains nested string literals is itself in a Java string literal.
Perhaps the simplest thing to do is to use escaped double-quotes within your JavaScript string for one set of quotes. I've opted for the outer set here:
eventFiringWebDriver.executeScript("document.querySelector(\"[ng-reflect-title='Assessment']>div.cc-tile>div.cc-tile-body\").scrollTop=370");
An alternative would be to escape the inner quotes in your JavaScript fragment, so that the following JavaScript would be run instead:
document.querySelector('[ng-reflect-title=\'Assessment\']>div.cc-tile>div.cc-tile-body').scrollTop=370
However this approach gets messy because you then have to escape the backslashes in your Java string so that they get passed on to JavaScript to escape the single quotes. Two levels of character escapes can be confusing to read, so this is best avoided.
来源:https://stackoverflow.com/questions/52431550/selenium-eventfiringwebdriver-javascript-syntaxerror-missing-after-argument