How to store an execute script in a variable

I want to store a script used for execute script in a variable to make it easier to call each time. I have found that executeScript interprets the data differently if it is in a variable or not. For example, I have the following script that opens up the about page from Google.com (and it works):

{
“Name”: “Google”,
“CreationDate”: “2019-10-31”,
“Commands”: [
{
“Command”: “open”,
“Target”: “https://www.google.com/”,
“Value”: “”
},
{
“Command”: “executeScript”,
“Target”: “document.querySelector("#hptl > a:nth-child(1)").click()”,
“Value”: “”
}
]
}

When I go to convert the click() into a variable, it doesn’t work:

{
“Name”: “Google”,
“CreationDate”: “2019-10-31”,
“Commands”: [
{
“Command”: “open”,
“Target”: “https://www.google.com/”,
“Value”: “”
},
{
“Command”: “store”,
“Target”: “document.querySelector("#hptl > a:nth-child(1)").click()”,
“Value”: “CLICK_ABOUT”
},
{
“Command”: “executeScript”,
“Target”: “${CLICK_ABOUT}”,
“Value”: “”
}
]
}

How can I go about saving my statement “document.querySelector("#hptl > a:nth-child(1)").click()” into a variable and then calling it with executeScript?

Your code have error and not working.

Write the command do you want because your command have not any function

document.querySelector(”#hptl > a:nth-child(1)").click()

What is this command ?

In Kantu show it’s a wrong code.

It’s Javascript. Eval is required in this case.

Example with store and executeScript without errors:

{
  "Name": "test-js-click",
  "CreationDate": "2019-11-1",
  "Commands": [
    {
      "Command": "open",
      "Target": "https://www.google.com/",
      "Value": ""
    },
    {
      "Command": "store",
      "Target": "document.querySelector(\"#hptl > a:nth-child(1)\").click();",
      "Value": "CLICK_ABOUT"
    },
    {
      "Command": "executeScript",
      "Target": "eval ${CLICK_ABOUT};",
      "Value": ""
    }
  ]
}
1 Like

This is the solution I needed. The eval was what I was missing. Thanks!