Search code examples
javascriptapplescriptmacos-monterey

Applescript: Safari "Do Javascript" No Longer Returns Booleans?


This used to return either true or false:

tell application "Safari" to do JavaScript "document.querySelector(\"video\") == null" in document 1

However, now, on macOS 12.0.1 on an M1 MBP, it doesn't seem to return anything (missing value) and the following convoluted wrapper seems necessary to get the former result:

tell application "Safari"
    set result to do JavaScript "if (document.querySelector(\"video\") == null) {
   1
} else {
   0
}" in document 1
    return result is 1
end tell

Another weird thing is that it's only booleans that don't get returned. The following returns 3.0:

tell application "Safari" to do JavaScript "3" in document 1

Any idea what changed? Is there a better way to get the boolean result back?

Here is what my Safari Develop tab looks like in case any of those settings are relevant: enter image description here


Solution

  • I still don't know why the issue is happening, but here's a temporary workaround in case it helps:

    tell application "Safari"
        
        set result to do JavaScript "try {
        var jsResult = document.querySelector(\"video\").paused;
    
        switch (jsResult) {
        case true:
            jsResult = 'js2as-true';
            break;
        case false:
            jsResult = 'js2as-false';
        }
    jsResult
    }
    catch(err) {
    'js2as-error' + err.message
    }" in document 1
        
        if (result = "js2as-true") then
            return true
        else if (result = "js2as-false") then
            return false
        else if (result starts with "js2as-error") then
            set errMsg to text 12 thru -1 of result
            error errMsg
        else
            return result
        end if
    end tell
    

    One limitation is that it's hard to make generic because you need to explicitly store the return value from the appropriate statement. Another approach might be to insert the script into an anonymous function, but then you'd have to explicitly return aValue