Applescript to open current Firefox 4 tab in Google Chrome - google-chrome

I'm attempting to write an applescript for Apptivate to open the current Firefox 4 or Safari tab in Google Chrome. The Safari section works and the if statement steps in to Firefox but it doesn't copy the URL.
Here is my applescript and it doesn't work:
tell application "System Events"
set myApp to name of first application process whose frontmost is true
if myApp is "firefox-bin" then
tell application "Firefox" to set theURL to the «class curl» of frontmost of window 1
tell application "Google Chrome"
activate
tell application "System Events" to keystroke "t" using {command down}
set URL of last tab of window 1 to theURL
end tell
else if myApp is "Safari" then
tell application "Safari" to set theURL to the URL in document 1
tell application "Google Chrome"
activate
tell application "System Events" to keystroke "t" using {command down}
set URL of last tab of window 1 to theURL
end tell
end if
end tell
What am I missing?

This might be tricky, but you can use keyboard shortcuts to copy and open the URL you want in Chrome. Check the code:
set backupClipboard to the clipboard
on ApplicationIsRunning(appName)
tell application "System Events" to set appNameIsRunning to exists (processes where name is appName)
return appNameIsRunning
end ApplicationIsRunning
on copyURL(appName)
tell application appName to activate
tell application "System Events"
keystroke "lc" using command down
end tell
delay 0.2 -- to make sure keystroke will hit cmd+l & cmd+c
end copyURL
if ApplicationIsRunning("firefox-bin") then
copyURL("Firefox")
else if ApplicationIsRunning("Safari") then
copyURL("Safari")
else
return
end if
tell application "Google Chrome"
open location (the clipboard)
activate
end tell
set the clipboard to backupClipboard
This script will first save your current clipboard, then it will check which browser is open. You can define the priority of browsers by sorting the if statement.
This is the same as pressing cmd+L (select url) and cmd+C (copy) on your browser.
Also, you can adapt the code to support other browsers.
(ApplicationIsRunning function from: http://vgable.com/blog/2009/04/24/how-to-check-if-an-application-is-running-with-applescript/)

I am running OS 10.4.11 on a PPC, I seem to find problems with the script with things like 'foo tab'. I think the issue is i have such an old device that the scripting won't recognize these newer commands. Maybe it is me.
Anyways, I wanted to be able to trigger a copy of a URL from Firefox to Safari using my Magic Mouse, running the magicmouse.jp driver. I got it to work using the following:
tell application "Firefox" to activate
tell application "System Events"
keystroke "lc" using command down
end tell
tell application "Safari" to activate
delay 1
tell application "System Events" to keystroke "l" using {command down}
--delay 0.2
tell application "System Events" to keystroke "v" using {command down}
tell application "System Events" to keystroke return
##############
cheers.
P.S. As a side note, some research on this brings up a number of people who disable flash in Safari and then trigger a copied URL to open within Chrome, which apparently must be a safer container, for what it's worth.

Related

Saving a page and clicking on the save popup in chrome using AppleScript

I want to download a txt file, opened in a tab in chrome using AppleScript. I want the save as dialog of Mac to provide the default extension and the name of the file.
tell application "Google Chrome" to tell active tab of window 1 to save as "r1.txt"
I tried this approach, and some other approaches like
activate application "Google Chrome"
tell application "System Events"
tell process "chrome"
keystroke "s" using {command down}
delay 1
click button "Save" of sheet 1 of window 1
end tell
end tell
still am not able to click the save button in the modal.
This works for me using the latest version of Google Chrome and the latest version of MacOS Mojave
activate application "Google Chrome"
tell application "System Events"
repeat while not (exists of menu bar item "File" of menu bar 1 of application process "Chrome")
delay 0.1
end repeat
click menu bar item "File" of menu bar 1 of application process "Chrome"
repeat while not (exists of menu item 11 of menu 1 of menu bar item "File" of menu bar 1 of application process "Chrome")
delay 0.1
end repeat
click menu item 11 of menu 1 of menu bar item "File" of menu bar 1 of application process "Chrome"
repeat while not (exists of UI element "Save" of sheet 1 of window 1 of application process "Chrome")
delay 0.1
end repeat
click UI element "Save" of sheet 1 of window 1 of application process "Chrome"
end tell
My approach to this problem was to try and avoid scripting the UI if possible, which can be problematic and unreliable. Instead, I decided to use the shell command curl to do the downloading job for us instead of trying to manipulate Chrome into doing it.
All we need is the location of where to save the file to, which I've set as the location to which Google Chrome defaults to, namely ~/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
It's a longer script than your present one, but most of it is declarations of variables (and properties), after which the script does two simple things:
Grabs the URL of the active tab in Chrome, and downloads the contents of that URL into the specified folder, retaining the same filename and extension as the remote file;
Once the download is complete, it reveals the file in Finder.

Applescript - open a new tab

My AppleScript abilities are rather limited, so please forgive what may be a simple question.
I have this script as an Automator Service which will open a series of aliases in new windows.
Triggered by key command in Finder via prefs>keyboard>shortcuts>services.
Service receives selected files or folders in Finder
on run {input, parameters}
repeat with aFile in input
tell application "Finder"
try
set origFile to original item of aFile
set aWindow to make new Finder window
set aWindow's target to origFile's parent
select origFile
end try
end tell
end repeat
end run
I'd like to try open in tabs instead, preferably without resorting to GUI scripting.
set aWindow to make new Finder window appears to have no equivalent set aWindow to make new Finder tab & scouring Apple's online documentation for 'make' or 'tab' has proven pretty fruitless... or rather much fruit, all of the wrong variety :/
I have a GUI version from another source
on new_tab()
tell application "System Events" to tell application process "Finder"
set frontmost to true
tell front menu bar to tell menu "File" to tell menu item "New Tab"
perform action "AXPress"
end tell
end tell
end new_tab
so, failing the direct approach, how could I fold this into my existing script?
MacOS 10.13.4
With the macOS defaults for both the Open folder in tabs instead of new windows preference in Finder unchecked, and the Dock preference Prefer tabs when opening documents: in System Preferences set to In Full Screen Only, then the following example AppleScript code should work as wanted with incorporating your original AppleScript code and the code of the new_tab handler.
on run {input, parameters}
set madeNewWindow to false
repeat with i from 1 to count input
tell application "Finder"
if (kind of item i of input) is equal to "Alias" then
set origFile to original item of item i of input
if not madeNewWindow then
set theWindow to make new Finder window
set madeNewWindow to true
else
my makeNewTab()
end if
set theWindow's target to origFile's parent
select origFile
end if
end tell
end repeat
end run
on makeNewTab()
tell application "System Events" to tell application process "Finder"
set frontmost to true
tell front menu bar to tell menu "File" to tell menu item "New Tab"
perform action "AXPress"
end tell
end tell
end makeNewTab
On my system it was not necessary for me to use the delay command however, delay commands may or may not be needed on your system and if so, add as necessary while adjusting the value as appropriate.
Coded for use in a Run AppleScript action in an Automator service where Service receives selected [files or folders] in [Finder].
Requires Finder to be added to Accessibility under Security & Privacy in System Preferences.
Tested under macOS High Sierra.
Note: The example AppleScript code is just that and does not employ any other error handling then what's shown and is meant only to show one of many ways to accomplish a task. The onus is always upon the User to add/use appropriate error handling as needed/wanted.
AppleScript to open Tabs in Finder from a list of paths in POSIX
Running this in the application Script Editor opens a predefined list of tabs from a list that one can set in normal POSIX file path, like /path/to/folder-or-file. To get a link to your folder or file, either press CMD+i or press File->Get Info in the menu (or just right-click on the file/folder itself). In the small window popping up, copy the path from the field named General -> Where: or get it from the terminal using print working directory (pwd) command and copy-pasting into the item-vars in the script below. Using a repeat loop we go through the vars included in the list and pull up one tab for each item. Very handy for those projects that use the same folders but lots of them!
on convertPathToAlias(thePath)
tell application "System Events"
try
return (path of disk item (thePath as string)) as alias
on error
return (path of disk item (path of thePath) as string) as alias
end try
end tell
end convertPathToAlias
set item1 to "/Users/username/Desktop/myfolder1"
set item2 to "/Users/username/Desktop/myfolder2"
set item3 to "/Users/username/Desktop/myfolder3"
set item4 to "/Users/username/Desktop/myfolder4"
set myList to {item1, item2, item3, item4}
set default_path to convertPathToAlias(item1)
tell application "Finder"
activate
open default_path
end tell
repeat with theItem in myList
set current_path to convertPathToAlias(theItem)
tell application "System Events" to keystroke "t" using command down
delay 0.3
tell application "Finder" to set target of front window to current_path
end repeat
using the initial function convertPathToAlias() we convert a normal path into the Applescript alias format. Read more about Applescript folders and files actions here.
I also added the delay command as the finder sometimes has an issue with loops and pulling up new tabs. At least on my machine.
This is based off a script with static links to folders.
To make this script import an external TXT file, check out this post on how to turn a text file into a list and run this from that instead!

Learning Applescript: Trouble linking to Safari

Run Down
Hello, this is a very specific and situation question. Basically, I'm running Applescript in Automator on Safari, and the result is Null.
What I Have
I currently have a script that can do these things:
Before I even run the Automator program, I have Safari open
Next I run the Automator, which starts with this code:
on run {input, parameters}
tell application "Safari" to activate
tell application "System Events"
keystroke "t" using command down
end tell
return input
end run
This script will activate Safari, and open a new tab.
Next I have an Automator pause. This will give the page time to load
After the Safari page has opened, I run this code:
on run
clickID("75610556")
end run
on clickID(theId)
tell application "Safari"
do JavaScript "document.getElementById(‘” & theId & “‘).click();" in document 1
end tell
end clickID
This script should of selected the button with the ID "75610556", but it did not. This is the key problem with my program.
Next I run the following code:
on run {input, parameters}
tell application "Safari" to activate
tell application "System Events"
keystroke "w" using command down
end tell
return input
end run
This closes the current tab.
Next, I loop through with an Automator loop.
What I Would Like Help With
I will address my questions for the program step by step.
For step one, is this a good way to set things up? Is Automator even a proper way to go?
Is this code efficient? Any errors yet?
I really hope there is an alternative to this. I have not found one.
Why won't this work in Safari? I feel like I have done this right.
Same as number 2, just curious if this is the best way to handle this
I think this is a good way to do things.
Why I Need This + Every Single Detail (Optional Section)
These are extra details if you want them. It will give you nearly every detail, and explain why I need this.
So there is a business contest at my college. I'm a freshman programmer, and have programmed a very simple mobile networking game. The issue is there is a cash prize foe $3,000 on a poll website. This website is Poll Everywhere. The judges did not realize that this website is not secure in the slightest. We reported it, and the judges thought it was not good enough of a reason to cancel the poll and maybe search for a new alternative. We reported that Poll Everywhere can be manipulated to work to any teams advantage who was smart enough to:
A. Turn off cookies for their browser
B. Use a private browser
But of course, the judges did not listen. They thought that if somebody stayed up all night, it might change it, but during a 2-3 hour period, it will have little effect. To deter their ruling, I would like to make an example program for them on my Mac that will blow their minds: A voting program. This program will open safari. Safari has already been configured to open the voting page in private browser mode. All my program has to do is open a new tab, find the button ID, and click on it. The faster it does this the better.
Final note: Was the back story too much? I know Stack overflow has a "spare the details" policy. I thought the elaborate version might help, but if it is a bad thing I will remove it.
Unfortunately I don't have a lot of time to answer all your questions as it's late and I need to get to bed, but here is an example of all you need to do. No need for automator, that just seems to complicate your process to me.
You may want to tweak some of the sleep settings a little if you need more "wait" time, I tried this on my local web server and it worked, but it's local so the site loads very fast.
on run
set i to 1
repeat until i > 5
do shell script "sleep 2"
tell application "Safari"
activate
tell window 1
set properties of current tab to {URL:"http://yoururl.com"}
end tell
end tell
do shell script "sleep 3"
tell application "Safari"
tell document 1
do JavaScript "document.getElementById(\"75610556\").click();"
end tell
quit
end tell
set i to i + 1
end repeat
end run
Also note, you'll need to change the url to your url where it says "http://yoururl.com" and you'll probably want to change the 5 in repeat until i > 5 to a larger number to let it repeat more.

How to start Sublime Text with selected project using a local .sublime-project file?

I may be missing the obvious, but can't seem to solve this fairly simple & typical case (with v3 build 3022 on Debian or XP, in case it matters):
Start Sublime Text opening a project "myprj", specified on its command-line,
using default.sublime-project located under that project's dir (say "/repo/myprj"),
automatically re-opening the last open files of that project (i.e. its workspace),
using default.sublime-workspace for that (also from the same project dir)
but (obviously) not auto-opening any other files remembered from non-project sessions,
and automatically saving all open files (to the above default.sublime-workspace) on exit.
Ideally:
$ sublime_text --project /repo/myprj/default.sublime-project
should just work. But it doesn't (see below).
Another approximation that seemed reasonable:
setting "hot_exit" and "remember_open_files" to false, and then invoking ST with:
$ sublime_text --data /repo/myprj --project default.sublime-project
But ST3 either doesn't find the project file (via --data), unless I chdir there first (--data seems to be no longer supported?), and it either doesn't auto-open any workspace files from last time (despite a previous "Project / Save Workspace As..."), or, if I set "remember_open_files" back to true, it just re-opens the last open files regardless of the project given on the command line.
I guess the issue is the workspace file not being handled automatically for some reason, and I'm just missing some trivial step somewhere. (The official docs (and also the unofficial) seem to discuss command-line switches for OS X only, and asking for --help didn't actually help with this one.)
(Please note: I wouldn't like to launch ST first, and then switch to some project from inside manually, and I also don't want to store the sublime-project/-workspace files outside of the prj. dir.) Thanks a lot!
I seached for a solution for a similar problem these days and didn't find a proper way. So i created an automator app with a small apple script. Maybe this helps you too.
Open Automator and Choose news Application.
Create an action to start Sublime Text 2
Insert an action to perfom the following apple script:
delay 0.2
tell application "System Events"
tell process "Sublime Text 2"
tell menu bar 1
tell menu bar item "Project"
tell menu "Project"
tell menu item "Recent Projects"
tell menu "Recent Projects"
click menu item "~/yourproject.sublime-project"
keystroke "p" using {command down, shift down}
end tell
end tell
end tell
end tell
end tell
end tell
end tell
For anyone still looking to do this, you can launch the built-in command line tool and launch it with a project like so (Mac OSX):
"/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl" --project "absolute-path-to-your.sublime-project"

Applescript - Google Chrome activate a certain window

Do you guys know how to activate the n-th Google Chrome window with Applescript? For example, if I have three Google Chrome windows opened, how do activate the second?
I've tried many different combinations, e.g.:
tell tab 3 of window 2 to activate
I've also noticed that:
tell application "Google Chrome"
tell window 1 to activate
end tell
and,
tell application "Google Chrome"
tell window 2 to activate
end tell
produce the same results, it only activates the last window
opened, Is this a bug?
Thanks in advance :)
tl;dr
Using set index of window <n> to 1 isn't fully effective in that it doesn't truly activate the window - it does make it visible, though.
Workarounds (examples assume you want to activate window 2):
Yar's answer offers a pragmatic workaround, though it's not entirely clear why it works. It does, however, have the advantage of not requiring the calling application to be authorized for assistive access, unlike the following solutions.
user495470's answer hints at a robust and generic solution that also works with non-AppleScriptable applications:
tell application "System Events" to tell process "Google Chrome"
perform action "AXRaise" of window 2
set frontmost to true
end tell
Alternatively, use the AppleScript handler defined below as follows:
tell application "Google Chrome" to my activateWin(it, window 2)
While adayzdone's answer should work and almost does, there is a catch - which may or may not be a problem (observed on Chrome 21.0.1180.89 on Mountain Lion) [update: still applies as of Chrome 47.0.2526.106 on OSX 10.11.2]:
While the solution will show the desired window as the front window, Chrome will NOT treat it as the front window if a different window was previously active. You can tell by the inactive close/min/zoom title-bar buttons, by what window title the checkmark is next to, and by the fact that keyboard shortcuts such as Cmd-L will not apply to the desired window.
If your next action will be to click somewhere on the window anyway, this may not be a problem, as such a click will fully activate the desired window.
Otherwise, you can employ a reasonably robust GUI-scripting workaround (gratefully adapted from a generic solution here):
Update: Sadly, the problem of not actually activating the window whose index you set to 1 seems to affect ALL apps (experienced on OS X 10.8.3).
Here's a generic function that properly activates a given window in a given AppleScriptable app using GUI scripting.
# Activates the specified window (w) of the specified AppleScriptable
# application (a).
# Note that both parameters must be *objects*.
# Example: Activate the window that is currently the 2nd window in Chrome:
# tell application "Google Chrome"
# my activateWin(it, window 2)
# end tell
on activateWin(a, w)
tell application "System Events"
click menu item (name of w) of menu 1 of menu bar item -2 ¬
of menu bar 1 of process (name of a)
end tell
activate a
end activateWin
On a side note, what the OP tried - e.g., activate window 1 - seems to be broken in ALL apps on OS X 10.8.3 as well - while the underlying application is activated, the window spec. is ignored.
Here's the original, more didactic code:
tell application "Google Chrome"
# Each window is represented by the title of its active tab
# in the "Window" menu.
# We use GUI scripting to select the matching "Window" menu item
# and thereby properly activate the window of interest.
# NOTE: Should there be another window with the exact same title,
# the wrong window could be activated.
set winOfInterest to window 2 # example
set winTitle to name of winOfInterest
tell application "System Events"
# Note that we must target the *process* here.
tell process "Google Chrome"
# The app's menu bar.
tell menu bar 1
# To avoid localization issues,
# we target the "Window" menu by position - the next-to-last
# rather than by name.
click menu item winTitle of menu 1 of menu bar item -2
end tell
end tell
end tell
# Finally, activate the app.
activate
end tell
Try:
tell application "Google Chrome"
activate
set index of window 1 to 1
delay 3
set index of window 2 to 1
end tell
As mklement mentioned, changing the index raises the window, but for example keyboard shortcuts are still registered by the previously frontmost window.
tell application "Google Chrome"
set index of window 2 to 1
end tell
Another option is to tell System Events to AXRaise window 1:
tell application "Google Chrome"
set index of window 2 to 1
end tell
tell application "System Events" to tell process "Google Chrome"
perform action "AXRaise" of window 1
end tell
Set the index and then open Chrome.
tell application "Google Chrome"
set index of window 2 to 1
delay 0.01
do shell script "open -a Google\\ Chrome"
end tell
Source
In addition to the solutions regarding activating the desired window, (at least) newer Chrome versions also support windows’ active tab index property:
tell window 1
set active tab index to 5
end tell
if you run this
activate application "Google Chrome"
tell application "System Events" to keystroke "`" using command down
it will do the whole thing even if its run from script editor.
heres another way, this one was already spelled out by someone else just in more steps:
tell application "System Events" to tell process "Google Chrome" to perform action "AXRaise" of window 2
activate application "Google Chrome"
if youre willing to save it as an application and assign it to a hotkey, you can do this:
tell application "Google Chrome" to set index of window 2 to 1
though i suppose at that point you may aswell simply hit command+`. Unless of course, your applescript involves a series of steps creating a series of steps, as is likely the case. If it involves a series of steps, something like the first line of the second code sample would be all you'd need, provided you assign it to a hotkey and hit the hotkey when chrome is already activated (or the line comes after chrome is activated in your code).