Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

pulsewidth947

macrumors 65816
Original poster
Jan 25, 2005
1,106
2
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 :)
 

iMeowbot

macrumors G3
Aug 30, 2003
8,634
0
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
 

pulsewidth947

macrumors 65816
Original poster
Jan 25, 2005
1,106
2
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.