Help with Safari Applescripting

Discussion in 'Mac Programming' started by pulsewidth947, Aug 13, 2005.

  1. pulsewidth947 macrumors 65816

    pulsewidth947

    Joined:
    Jan 25, 2005
    Location:
    squarefrog.co.uk
    #1
    I'm trying to write a script which opens a new tab using selected text as a url. For example, I select "www.hotscripts.org" then run the script which copies the selected text, opens a new tab, sets the url to "www.hotscripts.org". Only it doesnt work :)

    Heres my code:
    PHP:
    tell application "Safari" to activate
        tell application 
    "System Events" to keystroke "c" using command down
        set myData to 
    (the clipboard) as text
        tell application 
    "System Events" to keystroke "t" using command down
        tell application 
    "Safari" to set front document's URL to myData
    I cant get the script to copy the text. The reason I want this is because when you right click on selected text e.g. "http://www.apple.com/" you can choose go to address, but you cant do that when the http is omitted. And that bugs me :)
     
  2. iMeowbot macrumors G3

    iMeowbot

    Joined:
    Aug 30, 2003
    #2
    You have to cheat to get the selected text. Also, setting the URL via applescript wants proper syntax, so you have to cheat there too.
    Code:
    tell application "Safari"
    	activate
    	set myurl to (do JavaScript "getSelection()+''" in document 1)
    	tell application "System Events"
    		tell process "Safari"
    			keystroke "t" using command down
    			keystroke myurl
    			keystroke (ASCII character of 13)
    		end tell
    	end tell
    end tell
     
  3. pulsewidth947 thread starter macrumors 65816

    pulsewidth947

    Joined:
    Jan 25, 2005
    Location:
    squarefrog.co.uk
    #3
    Thanks for the reply.

    I ended up doing by GUI Scripting:

    Code:
    set the clipboard to ""
    tell application "Safari" to activate
    tell application "System Events"
    	tell process "Safari"
    		click menu item "Copy" of menu "Edit" of menu bar 1
    		set cb to the clipboard
    		if cb is not "" then
    			tell application "System Events" to keystroke "t" using command down
    			click menu item "Paste" of menu "Edit" of menu bar 1
    			click menu item "Reload Page" of menu "View" of menu bar 1
    		else
    			display dialog "Nothing selected"
    		end if
    	end tell
    end tell
    
    Some good ideas in your script.
     

Share This Page