Reputation: 35
I’m currently using AppleScript to automate some tasks in Safari. I have below code, which is supposed to set the value of the text box ‘ownerValue’ to the item from the loop. Whenever I execute the code, nothing happens.
set countryList to {"BR", "CN"}
repeat with country in countryList
tell application "Safari"
activate
tell document 1
do JavaScript "document.getElementById('ownerValue').value = country"
end tell
end tell
end repeat
When I replace the country in the loop to the actual country value, e.g. “BR”, it then inserts the text into the text field.
tell application "Safari"
activate
tell document 1
do JavaScript "document.getElementById('ownerValue').value = ‘BR'"
end tell
end tell
It also seems that AppleScript doesn’t recognise country as an item from the loop, since country is not in green.
Any ideas on how I can fix this so I can let AppleScript loop through the values in countryList?
Thanks!
Upvotes: 2
Views: 1391
Reputation: 7555
This will resolve the issue of the variable not being treated as a variable:
set countryList to {"BR", "CN"}
repeat with country in countryList
tell application "Safari"
activate
tell document 1
do JavaScript "document.getElementById('ownerValue').value = '" & country & "';"
end tell
end tell
end repeat
However, you may have another issue here, in that you are looping while inputing the value of a new variable into the same input field. In other words the JavaScript command as written is going to first input BR and immediately overwrite it with CN.
Note that the color of country
in the code above is not showing as green, however, here is a clipped screenshot from Script Editor and you see it's green.
To address the comment:
Could you please explain why it was previously not treated as a variable but now is?
When mixing two languages, i.e. AppleScript and JavaScript in this use case, and passing an AppleScript variable to JavaScript, you need to build out the JavaScript command using concatenation so the value of the variable is expanded.
In your code it was being treated as a fixed value as JavaScript has no way of knowing it was an AppleScript variable, hence concatenation, i.e. & ... &
. In AppleScript, &
is the concatenation character.
Upvotes: 2