In Chrome's JavaScript Console, I can type the following:
window.myVar = "myValue";
I can then access myVar
from the window context, where it returns "myValue"
. Excellent.
However, if I do the following in Applescript:
tell application "Google Chrome"
execute front window's active tab javascript "window.myVar = 'myValue';"
end tell
This execute statement appears to run when the script is called. No errors are thrown, and the Chrome window exists. But when I try to reference myVar
from the window context, only undefined
is ever returned. For testing purposes, I added in an alert statement after that declaration – the alert WILL fire, but myVar
remains unset.
Now, in Safari, using do JavaScript
with this same code works as if I'd typed the code directly into the console – myVar
returns a value.
Why doesn't Chrome fire these statements when called by Applescript when it can be done manually?
(Chrome 51.0.2704.84, OS X 10.11.5)
Best Answer
I discovered a workaround. Might not be the best, but the following line executes the JavaScript I have in mind while also setting properties of
window
:Using this,
myVar
properly returns"myValue"
. Nice.