Можно ли использовать AppleScript для открытия ссылки на новой вкладке в Safari?
Открыть URL-адрес на новой вкладке Safari с помощью AppleScript
Ответ 1
Это будет работать:
tell application "Safari"
tell window 1
set current tab to (make new tab with properties {URL:"http://www.stackoverflow.com"})
end tell
end tell
Ответ 2
Я думаю, что это также делает то, что вы просили, но оно намного короче и меньше зависит от браузера:
do shell script "open http://www.webpagehere.com"
Это откроет указанный URL в браузере по умолчанию. И если вы явно хотите открыть его в Safari, используйте это:
do shell script "open -a Safari 'http://www.webpagehere.com'"
Ответ 3
Обычно это создает новую вкладку и фокусирует ее (или фокусировать существующую вкладку, если URL уже открыт):
tell application "Safari"
open location "http://stackoverflow.com"
activate
end tell
Он открывает новое окно, если "Открывать страницы в вкладках вместо окон" никогда не установлено.
tell application "System Events" to open location
не работает с некоторыми URL-адресами, которые содержат символы, отличные от ASCII:
set u to "http://ja.wikipedia.org/wiki/漢字"
tell application "System Events" to open location u
--tell application "Safari" to open location u
--do shell script "open " & quoted form of u
Это открывает новую вкладку, даже когда новые страницы устанавливаются для открытия в окнах:
tell application "Safari"
activate
reopen
tell (window 1 where (its document is not missing value))
if name of its document is not "Untitled" then set current tab to (make new tab)
set index to 1
end tell
set URL of document 1 to "http://stackoverflow.com"
end tell
tell application "System Events" to tell process "Safari"
perform action "AXRaise" of window 1
end tell
set index to 1
не поднимает окно, но делает это окно как window 1
для системных событий, что может AXRaise
его.
Ответ 4
код:
tell application "System Events"
tell application "Safari" to activate
tell process "Safari"
click menu item "New Tab" of menu "File" of menu bar 1
end tell
end tell
tell application "Safari"
set URL of document 1 to "http://www.stackoverflow.com/"
end tell
Одна из проблем заключается в том, что это работает только в том случае, если системный язык установлен на английский.
Ответ 5
Я использовал следующий script, чтобы открыть сотни документов на вкладках в одном окне.
tell application "Safari"
tell window 1
make new tab with properties {URL:"http://foo.com/bar"}
make new tab with properties {URL:"http://foo.com/baz"}
end tell
end tell
Но это уже не работает в Safari 5.1 на Lion. Он откроет новую вкладку, но не будет загружать URL-адрес, указанный в glob свойства. Я изменил его на следующее, которое теперь работает:
tell application "Safari"
tell window 1
set URL of (make new tab) to "http://foo.com/bar"
set make new tab to "http://foo.com/baz"
end tell
end tell
Ответ 6
Прошло некоторое время, так как здесь был опубликован новый ответ. Я думаю, что это оптимальный способ сделать это. Он откроет Safari, если он не откроется, создайте новое окно, если нет открытых окон, и добавьте вкладку в текущее (или вновь созданное) окно.
tell application "Safari"
activate
try
tell window 1 to set current tab to make new tab with properties {URL:theURL}
on error
open location theURL
end try
end tell
Ответ 7
Я не могу прокомментировать: -/так я отвечу, чтобы сказать, что ответ Тима (выше) работает с OS X 10.8.5. Эта однострочная версия его script также работает:
tell window 1 of application "Safari" to set current tab to (make new tab with properties {URL:"http://www.stackoverflow.com"})
Arrgh - одна строка переполнена. Здесь он не содержит тегов кода:
сообщите окну 1 приложения "Safari", чтобы установить текущую вкладку (создайте новую вкладку со свойствами {URL: " http://www.stackoverflow. ком" })
Ответ 8
В итоге я использовал автомата для этого, что было намного проще, и он работает.
Ответ 9
Вы можете попробовать следующий подход:
//make Safari window active and topmost
tell application "Safari" to activate
//start communication with Safari
tell application "Safari"
tell window 1
//create new tab and open specified URL
tab with properties {URL:"https://url.com"})
//make tab active
set visible to true
end tell
end tell
Также вы можете комбинировать использование Apple script в FastScript (бесплатно для 10 ярлыков)
Чтобы добавить script - просто сохраните script в /Library/Scripts
. После того, как вы сможете установить ярлык для нового script.
Если вы хотите открыть новое окно, чем новая вкладка, вы можете играть в следующем:
tell application "System Events"
tell process "Safari"
click menu item "New window" of menu "File" of menu bar 1
end tell
end tell
Примечание. Вы должны разрешить AppleScript использовать специальные возможности в настройках безопасности в этом случае.
Ответ 10
Не самое короткое решение, но также работает, и не только на английском языке.
tell application "Safari"
activate
end tell
tell application "System Events"
set frontmost of process "Safari" to true
keystroke "t" using {command down}
end tell
set myURL to "anyurl.html"
delay 2
tell application "Safari" to set the URL of the front document to myURL
Ответ 11
Работал для меня в Safari v.11
tell application "Safari"
tell window 1
make new tab with properties {URL:"https://twitter.com"}
end tell
end tell
Ответ 12
Я нашел способ открыть новую вкладку в фоновом режиме с Safari.
tell application "Safari"
set the URL of (make new tab in window 1) to "your.url.net"
end tell
В то время как я написал этот ответ, я сделал это
tell application "Safari"
try
display dialog "Website URL" default answer "" buttons {"OK", "Annuler"} default button 1
set theURL to text returned of result
set netProto to "https://"
if theURL contains netProto then
set the URL of (make new tab in window 1) to theURL
else
set the URL of (make new tab in window 1) to netProto & theURL
end if
end try
end tell
Новая версия
tell application "Safari"
repeat
try
display dialog "Website URL" default answer "" buttons {"OK", "Annuler"} default button 1
set theURL to text returned of result
if theURL is "" then exit repeat
set netProto to "https://"
if theURL contains netProto then
set the URL of (make new tab in window 1) to theURL
else
set the URL of (make new tab in window 1) to netProto & theURL
end if
display dialog "Do you want to open a new tab?" buttons {"Yes", "No"} default button "Yes"
if button returned of result is "No" then exit repeat
end try
end repeat
end tell
Любые предложения будут оценены
С наилучшими пожеланиями