Similar to Return Javascript variable to AppleScript , I want to run JavaScript in Safari and return a value to AppleScript. This works:
tell application "Safari"
tell front document
set myVar to do JavaScript "function foo() {return 5;};result=foo()"
return myVar
end
end tell
The problem is that the function returning the variable is asynchronous, waiting for the server to respond a few times. This fails:
tell application "Safari"
tell front document
set myVar to do JavaScript "async function foo() {return 5;};result=foo()"
return myVar
end tell
end tell
with error Script Error: The variable myVar is not defined.
With javascript async function foo() {return 5;};result=await foo(), I get the same error.
The reason I want a value from the async function is that I'm automating a reply to messages on a website. One JavaScript function closes existing messages pop-ups, and waits until they all disappear (with const async_delay = ms => new Promise(res => setTimeout(res, ms)); and an await). Another JavaScript function opens the message pop-up I want and waits until it appears. For now, I am using a delay in AppleScript that is long enough. But the time required for JavaScript varies with the initial number of messages: if AppleScript waits too long, another pop-up message may appear in the meantime and the code sends a reply to the wrong person. Hence, it would be cleaner and more robust if I can fetch the result from asynchronous JavaScript.
Can AppleScript fetch variables from async JavaScript?
return. He says not to use one. stackoverflow.com/questions/23224563/…