Мой подход к этой проблеме состоял в том, чтобы попытаться избежать сценариев пользовательского интерфейса, если это возможно, что может быть проблематичным и ненадежным. Вместо этого я решил использовать команду оболочки curl
, чтобы выполнить загрузку за нас, вместо того, чтобы пытаться манипулировать Chrome для ее выполнения.
Все, что нам нужно, это место, куда нужно сохранить файл, которое я установил в качестве местоположения, по умолчанию Google Chrome , а именно ~/Downloads
.
property path : "~/Downloads" -- Where to download the file to
use Chrome : application "Google Chrome"
property sys : application "System Events"
property window : a reference to window 1 of Chrome
property tab : a reference to active tab of my window
property URL : a reference to URL of my tab
property text item delimiters : {space, "/"}
on run
-- Stop the script if there's no URL to grab
if not (my URL exists) then return false
-- Path to where the file will be saved
set HFSPath to the path of sys's item (my path)
-- Dereferencing the URL
set www to my URL as text
-- Extract the filename portion of the URL
set filename to the last text item of www
-- The shell script to grab the contents of a URL
set sh to the contents of {¬
"cd", quoted form of the POSIX path of HFSPath, ";", ¬
"curl --remote-name", ¬
"--url", quoted form of www} as text
## 1. Download the file
try
using terms from scripting additions
do shell script sh
end using terms from
on error E
return E
end try
## 2. Reveal the downloaded file in Finder
tell application "Finder"
tell the file named filename in the ¬
folder named HFSPath to if ¬
it exists then reveal it
activate
end tell
end run
Это более длинный скрипт, чем ваш нынешний, но в большинстве своем это объявления переменных (и свойств), после чего скрипт выполняет две простые вещи:
Захватывает URL активной вкладки в Chrome и загружает содержимое этого URL в указанную папку, сохраняя то же имя файла и расширение, что и удаленный файл;
После завершения загрузки файл обнаруживается в Finder .