Search code examples
javascriptapplescript

The issue about importing variable into javascript in AppleScript


I meet an issue when I imported a variable(got from javascript A)to the javascript B, here is my script code:

tell application "Safari"
    tell tab 6 of window 1
        set varA to do JavaScript "document.getElementById('idA').textContent." as string
    end tell
    tell tab 7 of window 1
        do JavaScript "
        document.getElementById('idB').value=" & varA & ";"
    end tell
end tell

And I found when varA contains non-number content, it couldn't be imported to the input filed of "idB", I don't understand.....

I tried to return var A in AppleScript, it shows the value correctly. And I tried to

"set varB do JavaScript "
document.getElementById('idB').value=" & varA & ";"

When I return var B in AppleScript, it shows error number -2753.

I hope the script can help me to get the value from webpage A and input it to a specific input filed on webpage B.


Solution

  • if varA is not a number, you need to put quotes around the value in the assignment statement. Otherwise it will treat it as an expression to evaluate.

        tell tab 7 of window 1
            do JavaScript "
            document.getElementById('idB').value='" & varA & "';"
    

    Not that if varA contains single quote or backslash characters, you'll need to escape them. See Does AppleScript have a replace function? for ways to do text replacement in AppleScript.