Is there a way to determine programmatically, using Python, which web page is currently active in Safari?
A:
May I suggest mind reading. One program usually cannot infer the inner state of another program.
But maybe you could write a bookmarklet (in JavaScript!) to expose the information to Python when clicked.
Jan B. Kjeldsen
2010-03-04 14:42:39
@Jan, in Mac OS X properly coded applications can (reasonably easily) "mind read" each other, as you put it, thanks to OSA, Apple's scripting architecture. This is mainly intended for AppleScript, Apple's proprietary and peculiar scripting language, but as I show in my answer third party modules such as appscript make it pretty easy to access that wealth of functionality from Python too!
Alex Martelli
2010-03-04 15:11:38
+5
A:
An Applescript example is here, and the relevant part is:
tell application "Safari"
set url_list to URL of every document
end tell
Python/AppleScript translation is covered here. E.g., install appscript as described here:
sudo easy_install appscript
and then, as shown here, you can do e.g.:
>>> import appscript
>>> print appscript.app("Safari").windows.first.current_tab.URL()
http://wiki.python.org/moin/MacPython/Safari
Alex Martelli
2010-03-04 15:09:29
@Alex One caveat of this solution is that whenever I have it running a Python application icon pops up bouncing in the dock. If I close the application, it closes my python script, so I know the two are related. I'm wondering if you know a way for me to run the script without getting the Python program in the dock.
Chris Redford
2010-03-11 21:03:53
Does the bouncing happen if you are running your script with a `Terminal.app`? Or how else are you packaging your `.py` file to obtain the "unwanted bounce" effect?
Alex Martelli
2010-03-11 21:19:11
It happens whether I run the `.py` script in `Terminal.app`, `TextMate.app`, or as a `launchd` agent. And just so it is unambiguous, the primary problem is that I don't want Python to be in the dock (i.e. I want the script to run quietly in the background).
Chris Redford
2010-03-12 13:20:17
@credford, I'm perplexed -- I run py scripts in Terminal all the time and don't see the bounce. Don't think we can solve it in these cramped comment boxes:-(. Please open another Q giving a minimal example that bounces when run from the terminal and both myself and others will strive to help, as usual on SO -- thanks.
Alex Martelli
2010-03-12 15:36:31