Search code examples
macosapplescriptnsuserdefaultsuserdefaults

How to convert window object to string in AppleScript?


I've an AppleScript that retrieves window id of an app. Example following script retrieves the window id of Brave Browser.

set urls to {"https://google.com"}
tell application "Brave Browser"
    set myNewWindow to make new window
    repeat with theURL in urls
        tell myNewWindow to open location theURL
    end repeat
    delay 0.3
    log myNewWindow
    return class of myNewWindow //comment - returns "window" as a class
end tell

My goal is it possible to convert the window id to a string and vice-versa.

Why conversion?

  • I want to save window id in UserDefaults on macOS.

Note: This AppleScript is used in macOS app.


Solution

  • To be honest, it's hard for me to understand why the ID should be kept in defaults. Because theID variable will already store this value throughout the script. And at any time you can close the window using a variable in a later part of the script. I can only assume one thing: you want to open a window locally and then close it from other script executed on a remote machine.

    And getting the window ID in Brave Browser as text is easy:

    set urls to {"https://google.com"}
    tell application "Brave Browser"
        set myNewWindow to make new window
        repeat with theURL in urls
            open location theURL
        end repeat
        delay 0.3
        set theID to (id of myNewWindow) as text --> the ID of window in  text form
    end tell
    
    -- write theID value to defaults here
    

    Closing the window from other script:

    -- first, read theID from defaults here
    
    tell application "Brave Browser"
        close window id (theID as integer)
    end tell