heymega
heymega

Reputation: 9411

Write Cookie Programmatically to Safari

Requirement:

On a Mac, write a cookie in Safari to a particular domain on startup.

So far the options I can think of are.

1. Safari's cookie file

On startup, write the cookie directly to Safari's binary file located in ~/Library/Cookies/Cookies.binarycookies. However, I don't know if this is possible and cannot find any documentation on it. I'm reluctant to try this incase the file has a checksum against it.

2. Get Safari to set it

On startup, using AppleScript, launch Safari silently/hidden and navigate to a site which sets the cookie.

I'm predominantly a c# windows developer so I'm a little out of my comfort zone here.

Upvotes: 1

Views: 1500

Answers (1)

William T Froggard
William T Froggard

Reputation: 738

Since cookies are shared globally on OS X, you can use this little bit of AppleScript/ObjC to add cookies from a website by loading the website in an invisible WebView, which just gets released once the loading is done, and the cookies have been saved. Note that you have to create a "Cocoa-AppleScript Applet" from the "New from Template" menu in the File menu of Script Editor.

display alert set_cookies_for_URL("http://www.apple.com")
(* AppleScript's handlers all seem to become unusable after importing frameworks.
 * To compensate, I'm relegating AppleScript/ObjC calls to the end of the file
 *)
use framework "WebKit"

on set_cookies_for_URL(URL)
    set web_view to current application's WebView's alloc()'s initWithFrame:(current application's NSMakeRect(0, 0, 500, 500)) frameName:"tempFrame" groupName:"tempGroup"
    set web_view's mainFrameURL to URL
    #delay to avoid release
    repeat while ((web_view's isLoading) as boolean) is true
        delay 1
    end repeat
    return "done"
end set_cookies_for_URL

Upvotes: 2

Related Questions