How to execute pre-defined JavaScript function in AppleScript and pass data to JavaScript

applescriptgoogle-chromejavascriptjavascript-automation

In my AppleScript, I want to pass a list of keys to a website's client-side, then query the data on the backend, and get the response and re-render the client-side. All of these should happen in the background so that the user won't notice it.

Previously, I was able to create a dummy button (set it as a hidden button), and click the button in AppleSciprt, then trigger the onClick event in my website:

tell tab t to set RemoveBtRestriction to execute javascript "document.getElementById('myButton').click()"

But now my requirement is to pass data to the client, how to achieve this? Is it possible to execute a JavaScript function like this directly, which the loadKeys function is pre-defined my client-side:

set keys = 'key1,key2,key3'; 
tell tab t to execute javascript "loadKeys(keys)"

Any ideas would be appreciated, thanks in advance!

Best Answer

Compose the JavaScript string using the concatenation operator in AppleScript.

"loadKeys(" & keys & ")"

This will run the JavaScript loadKeys(key1,key2,key3).