An unexpected issue occurred while trying to run Javascript through seleniumChromeDriver: Runtime.evaluate error

I've been facing an issue while trying to run Javascript within python's selenium Chromedriver. Despite researching the error mentioned in this link unknown error: Runtime.evaluate threw exception: SyntaxError: Unexpected token var and attempting to properly format the js as suggested, I couldn't resolve the problem.

The script I'm using is:

    $.ajax({
    type: "POST",
    data:  {
        "code": "a=input(\"\");\nprintf(\"Part A\\n\");\nSA=6*a^2;\nprintf(\"SA = %d\\n\",SA);\nr1=(6*a^2/(4*pi))^(1/2);\nprintf(\"Radius = %.2f\\n\",r1);\nprintf(\"Part B\\n\");\nv=a^3;\nr2=(3*v/(4*pi))^(1/3);\nprintf(\"Radius = %.2f\\n\",r2);\n",
        "input": "",
    },
    url: "code.evaluate.abc.php",
    dataType: "json",
    });

As it's not possible to input this code directly into driver.execute_script(javascript_string) due to newlines, I had to remove them to condense it into one line:

$.ajax({type: "POST",data:  {"code": "a=input(\"\");\nprintf(\"Part A\\n\");\nSA=6*a^2;\nprintf(\"SA = %d\\n\",SA);\nr1=(6*a^2/(4*pi))^(1/2);\nprintf(\"Radius = %.2f\\n\",r1);\nprintf(\"Part B\\n\");\nv=a^3;\nr2=(3*v/(4*pi))^(1/3);\nprintf(\"Radius = %.2f\\n\",r2);\n","input": "",},url: "code.evaluate.abc.php",dataType: "json"});

This condensed version functions correctly when pasted into the browser's developer console, but running it from inside driver.execute_script results in the following error:

WebDriverException: unknown error: Runtime.evaluate threw exception: SyntaxError: Invalid or unexpected token (Session info: chrome=65.0.3325.162) (Driver info: chromedriver=2.35.528139 (47ead77cb35ad2a9a83248b292151462a66cd881),platform=Linux 4.13.0-37-generic x86_64)

P.S.: Console.log, alerts, small javascript commands, and other webdriver commands execute without any issues.

Answer №1

When executing the following JavaScript code in the Browser's Developer Console:

$.ajax({type: "POST",data:  {"code": "a=input(\"\");\nprintf(\"Part A\\n\");\nSA=6*a^2;\nprintf(\"SA = %d\\n\",SA);\nr1=(6*a^2/(4*pi))^(1/2);\nprintf(\"Radius = %.2f\\n\",r1);\nprintf(\"Part B\\n\");\nv=a^3;\nr2=(3*v/(4*pi))^(1/3);\nprintf(\"Radius = %.2f\\n\",r2);\n","input": "",},url: "code.evaluate.abc.php",dataType: "json"});

The code functions properly in the browser but encounters issues with ChromeDriver. This seems to stem from a version compatibility problem between the binaries being used:

  • The current version of chromedriver=2.35
  • According to the Release Notes for chromedriver=2.35, it only supports Chrome v62-64
  • Your chrome version is 65.0
  • Release notes for ChromeDriver v2.37 state support for Chrome v64-66

This highlights an inconsistency between the ChromeDriver version (v2.35) and the Chrome Browser version (v65.0)

Resolution

  • Upgrade ChromeDriver to ChromeDriver v2.37
  • Maintain Chrome at version Chrome v65.x levels (referencing ChromeDriver v2.37 release notes)
  • Clean your Project Workspace using your IDE and rebuild with necessary dependencies only
  • Utilize CCleaner to clear OS tasks before and after running your test suite
  • If your base Web Client is outdated, uninstall via Revo Uninstaller and install latest version
  • Execute your @Test

Answer №2

To incorporate JavaScript into my Python code seamlessly, I would utilize Python's multiline string functionality.

driver.execute_script("""

var JS={"abc": "def"}

console.log(JSON.stringify(JS));
""")

By using this method, I can ensure there are no escaping issues to contend with.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In Javascript, merge two objects while maintaining their original references

Here's a basic illustration of my goal: data = {name: 'fred'}; newData = {}; newData.name = data.name; newData.name = 'ted'; console.log(data.name); // I expect this to be ted instead of fred I am wondering if it is feasible i ...

How to properly cast interfaces when using Angular 4's HttpClient to fetch items

Here is the layout of my interface interface IPlacesResult { summary: { queryTime: number; // ... }; results: { id: string; // ... address: { streetNumber: number; // ... }; }[]; } To populate this interface, I ...

Vue.js - Capturing a scroll event within a vuetify v-dialog component

Currently, I am working on a JavaScript project that involves implementing a 'scroll-to-top' button within a Vuetify v-dialog component. The button should only appear after the user has scrolled down by 20px along the y-axis. Within the v-dialog, ...

Searching for information in one array using a loop with another array (MongoDB and JavaScript)

I have two arrays that need to be compared for matching elements. let firstArray = [1, 2, 3] let secondArray = [{id:1}, {id:1}, {id:3}] I am trying to create a new array containing objects with the same id. Despite trying different approaches, I am unabl ...

What are the steps to establish a Z-axis coordinate system in three.js?

When working with three.js, the Y axis typically represents up and down, while the Z axis represents forward and backward. However, I want to switch this so that the Z axis represents up and down, and the Y axis represents forward and backward. Here is an ...

Tips for avoiding the "MongoError: Transaction 1 has already been committed." error

Challenge Currently using MongoDB version 4.2, I am facing a hurdle while trying to execute 50,000 transactions involving array mutations. Most of them are successful but for the remaining 10%, I encounter this error: MongoError: Transaction 1 has been ...

Here's a method to verify a function prop was invoked using react-testing-library

There are 3 key files: First File: utilities.js export const utilities = () => ({ func: () => 'Function was executed', }); Second File: AppComponent.js import React from 'react'; import { utilities } from './utilities&apo ...

Why is my website appearing on Google with the URL as the name?

After uploading my HTML, CSS and JavaScript website online (without the use of any frameworks or libraries like React or Next), I noticed that when I searched for it on Google, the URL showed up as the website name instead (see image here). Following the ...

What steps are involved in installing Angular 2 through NPM?

Currently, I am in the process of setting up my personal local development environment for an Angular 2 application without utilizing the QuickStart seed mentioned on the official Angular 2 website or the Angular CLI due to the surplus files that come with ...

Utilize CSS with dynamically created elements

I am currently figuring out how to use my .each() function with a $(document).ready and a click event. Here's what I have so far: $(document).ready(function(){ $(".help-inline").each(function() { $(this).css('display', 'none&apos ...

Experiencing problems uploading an image through ajax requests

Apologies if the title doesn't provide enough detail! The concept involves a div popup where users can enter their feedback and potentially upload a screenshot. Embedded within the page is the following javascript (called through ajax into a div). ...

Utilize jQuery to export HTML or JSON data to an Excel spreadsheet

I am looking for a way to export json or html data to an excel sheet using only html and jquery, without involving any server code. I have found some fiddles that allow me to download the excel sheet successfully, but unfortunately, none of them work in In ...

I am eager to run the code that I retrieved from the server. I have access to the code in my console and I desire for it to execute on the main browser page

Currently, I have a simple Google Chrome Extension that includes a button. By using AJAX, I am fetching a script from a server in my browser's console. Essentially, clicking on the extension reveals a button which, when clicked, fetches the script fro ...

What is the correct way to simulate pressing the ENTER key using the Robot class?

After successfully creating a method to click on a specific addon from the Firefox toolbar on Windows, I encountered an issue when trying to execute the same action from a Jenkins server running on a Linux machine. The problem arises when attempting to per ...

Utilizing Knockout to Load JSON Data in DevExtreme

As a newcomer to both javascript and devextreme, I am currently navigating my way through. I successfully created a webpage that loads a json file, but I'm facing challenges implementing it using devextreme. I have a dxDataGrid where I intend to disp ...

Increase the bottom padding or add some extra space to the Bootstrap form or page

I am currently working on enhancing a Bootstrap Form that includes reset/submit buttons positioned at the bottom. A common issue is when iPhone users attempt to click the Submit button, which initially displays Safari icons before requiring an extra tap to ...

Extract data dynamically from multiple JSON arrays using AngularJS

In the task at hand, I am faced with multiple JSON arrays and my goal is to extract specific data using a loop. Specifically, I am interested in obtaining the value of the key count. Let's take a look at the code snippet: .then(function(){ var t ...

"Contrasting the initialization of state in the constructor with managing state

Can you explain the distinction between these two methods of initializing state in ES6 other than their access to props? constructor(props) { super(props); this.state = { highlighted: 5, backgroundColor: '#f3f3f3', ...

Encountering a problem when verifying if the data is in JSON format using JavaScript

I'm using JavaScript to determine whether an input value is in JSON format, but I've encountered a problem with a specific value. Below is my code explanation. isJSON = async(str) => { try { return (JSON.parse(str) && !!str); ...

Access a SQL database to retrieve a data value and seamlessly integrate it into an HTML document with the help of node

I am new to web development and currently facing a challenge in displaying SQL content on an HTML page. My stack includes Node.js, Express, and SQLite3. I have a folder named public containing HTML, CSS, and JS files. The objective is to retrieve a varia ...