What could be causing the SyntaxError with JavascriptExecutor: Unexpected identifier?

Python

PythonExecutor py = (PythonExecutor) driver;
Boolean ready = (Boolean)py.executeScript("the following Python code");

Python Code

var ready = False;
window.onload = def check_ready():
    ready = True

def sleep():
    return new Promise(resolve => setTimeout(resolve, 2000))

for i in range(30):
    if ready:
        return True
    await sleep()
    
return False;

UPDATE: Apologies for the syntax error "funtion" in my previous post. It was a typo and not part of my actual code. Despite fixing all syntax errors, I still encounter "SyntaxError: Unexpected identifier".

The purpose of this code is to wait for a specified period for the page to finish loading. While I normally use document.readyState to determine this, there are instances where Chrome stops loading abruptly and document.readyState remains stuck for over 5 minutes. To counter this issue, I am experimenting with creating single-threaded code that simulates a multi-threaded process.

Given JavaScript's single-threaded nature (a limitation for such a versatile language), we must think outside the box.

This code functions properly in the browser console when replacing return true; with console.log('true'); and return false; with console.log('false');, so the problem doesn't seem apparent.

Answer №1

It appears that your JavaScript code contains some errors.

The first error can be found in the third line where you have written

window.sleep = funtion() { return new Promise(resolve => setTimeout(resolve, 2000)); }
, there seems to be a typo in the spelling of function.

The second mistake is using await without declaring async in your function definition. Remember, async is necessary to ensure that the function returns a promise, while await should only be used inside async functions.

The third issue arises when you try to return true; from within the for loop of an if condition, which is invalid because it is not enclosed within a function.

Another problem is that you are not invoking the window.onload function, resulting in a false return even after the page has loaded.

Furthermore, the usage of incomplete resolve in the window.sleep function raises uncertainty about its functionality.

Lastly, returning false at the end of the code without any context renders it meaningless.

I have made modifications to the code to address these issues effectively, feel free to review it below:

var status = false;
window.sleep = function() { 
    return setTimeout(() => {
        console.log("=> Waited for 2 seconds...");
    }, 2000);
}
var getStatus = function() {
    for(var i = 0; i < 30; i++) {
        if(window.onload = function() {
            return true;
            }) {
            status = true;
            console.log(i+"). Loaded ? "+status);
            break;
        } else {
            console.log(i+"). Loaded ? "+status);
            sleep();
        }
    }
    return status;
}
getStatus();

Feel free to test the following Java code snippet that prints true upon page loading :

System.setProperty("webdriver.chrome.driver", "C:\\NotBackedUp\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");
JavascriptExecutor js = (JavascriptExecutor) driver;
Boolean result = (Boolean) js.executeScript("var status = false;\r\n" + 
        "window.sleep = function() { \r\n" + 
        "   return setTimeout(() => {\r\n" + 
        "       console.log(\"=> Waited for 2 seconds...\");\r\n" + 
        "   }, 2000);\r\n" + 
        "}\r\n" + 
        "var getStatus = function() {\r\n" + 
        "   for(var i = 0; i < 30; i++) {\r\n" + 
        "       if(window.onload = function() {\r\n" + 
        "           return true;\r\n" + 
        "           }) {\r\n" + 
        "           status = true;\r\n" + 
        "           console.log(i+\"). Loaded ? \"+status);\r\n" + 
        "           break;\r\n" + 
        "       } else {\r\n" + 
        "           console.log(i+\"). Loaded ? \"+status);\r\n" + 
        "           sleep();\r\n" + 
        "       }\r\n" + 
        "   }\r\n" + 
        "   return status;\r\n" + 
        "}\r\n" + 
        "return getStatus();");
System.out.println(result);

I hope this modified version solves the previous issues...

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

Discover a variety of web element types with FindElements() in Selenium using C#

Hello everyone, I could really use some assistance with a programming issue I am facing. I have a method where I check for the presence of multiple web objects on a page and then click on them if they are present. The method is currently working as expecte ...

Is it possible to use the Husky "commit-msg" hook to git add new files?

I am currently setting up an automatic versioning system where if I use git commit with the message format PATCH: {message}, the app's patch version will automatically be updated (and the same for the prefixes MINOR and MAJOR as well). My approach inv ...

Show JSON data as choices in a dropdown menu

On my webpage, I want to display a dropdown list populated with objects from a JSON file using JavaScript. Here is the structure of my HTML and JSON: HTML <html> <body> <select id="myid">MyList</select> <script src="m ...

Is there a way to pause and await the completion of an axios post request within a different axios interceptor?

Here are my axios interceptors: instance.interceptors.request.use( (config) => { const accessToken = localStorage.getItem("access_token"); const auth = jwt_decode(accessToken); const expireTime = auth.exp * 1000; co ...

Tips for excluding specific elements when clicking on a document

JavaScript $(document).click( function () { alert("Hello there"); } Web Development <div id="wrapper"> <div id="inner-1"> <div id="sub-inner1">Sub Inner1 Content</div> <div id="sub-inner2">Sub Inner2 Content&l ...

Utilizing Node.js and Jasmine: Preventing the invocation of a Promise function to avoid executing the actual code results in DEFAULT_TIMEOUT_INTERVAL

There is a function below that returns a promise. public async getAverageHeadCount(queryParams: Params, childNode: any, careerTrackId: string): Promise<Metric> { const queryId = this.hierarchyServiceApiUrl + "rolling-forecast/ahc/" + q ...

Is there a way to command Selenium in Python to click on the open application button?

Hey there, can you help me figure out how to automate clicking the play button on Roblox using Python and Selenium? Here's the code snippet I've been trying: from selenium import webdriver from selenium.webdriver.chrome.service import Service fr ...

The issue of javascript Map not updating its state is causing a problem

I've encountered an issue where my components are not re-rendering with the updated state when using a map to store state. const storage = (set, get) => ({ items: new Map(), addItem: (key, item) => { set((state) => state.items ...

"Combining the power of Node.js, mysql, and socket.io

As a beginner with socket.io, I am facing an issue. How can I update and display real-time data from a table in my database without having to restart the node.js server? The table receives new data every 10 seconds. I have followed several tutorials but h ...

An error occurs in the console stating 'Maximum call stack size exceeded' when trying to add data to the database using JavaScript

I've been struggling with a JavaScript error for the past few days and despite scouring through numerous answers on StackOverFlow, none seem to address my specific issue. My goal is to simply submit a record to the database using a combination of Jav ...

Screening new elements to be included in the array

When adding new items to an array in my App, I encountered a problem with filtering the newly added items. If I use .filter by state, it modifies the original array and I am unable to filter from the beginning (original array). I attempted to filter using ...

Swapping values in JSON by comparing specific keys: A guide

I have JSON data that contains a key called reportData with an array of values: {"reportData":[ ["1185","R","4t","G","06","L","GT","04309","2546","2015","CF FE","01H1","20","23840","FF20"], ["1186","R","5t","R","01","L","TP","00110","1854","2016" ...

Ways to eliminate the blue selection box when dragging canvas objects in fabric framework

I've been trying to find a solution to remove the annoying blue highlight box that appears when dragging on the canvas while using fabric js, but so far I haven't had any luck. I've tried the following code, but it only works for text and n ...

Having trouble with my bootstrap carousel not functioning properly - issue with jQuery line causing the rest of the code to disable

I've been facing some challenges with this Bootstrap slider for quite some time now. Despite my best efforts and thorough research on the forum, I just can't seem to make it function properly. Here's the code snippet in question: <!DOCTY ...

The transition from Vuetify3's VSimpleTable to VTable is ineffective and unsuccessful

The v-simple-table component has been renamed to v-table Old code that was using v-simple-table may not work correctly after the renaming. It is recommended to use v-data-table with the same data, as it works correctly. https://i.sstatic.net/3GVdYMWl.png ...

Guide on incorporating geolib into React Native for distance calculation of two locations

Is there a simple way to calculate the distance between Longitude and Latitude in react native? I have the coordinates of my current location and destination, but keep encountering errors when attempting to use geolib for this calculation. I attempted to ...

Tips for decreasing the width of a Grid component in React using MUI

Is there a way to adjust the width of the initial Grid element within Material UI, allowing the remaining 3 elements to evenly occupy the extra space? see visual example Would modifying the grid item's 'xl', 'lg', 'md', ...

Convert a comma-delimited string containing a numerical value into a floating point number, for example, 3.00

I need to extract a number from a value that is returned with commas around it. My goal is to convert this value into a number so that I can compare it against another number in my code later on. However, I'm facing difficulties in reliably extracting ...

Setting orientations for portrait and landscape views using Material UI breakpoints

Looking to implement portrait and landscape views for tablets using the styles object in Material UI. const tabletStyles = theme => ({ root: { padding: theme.spacing.unit, [theme.breakpoints.up('md')]: { backgroundColor: theme ...

The reason why Express is not directing to the static React build files is due to the absence of a specific URL slug

The Scenario Currently, I'm in the process of developing a React application that is being served statically through Express. To clarify, the React app is constructed using npm run build and the resulting static files are stored within the build/ ...