I have written an AppleScript to automate my work setup and just need the final touch. I copy something to clipboard in my script; I need to edit the text I copied to leave only the last line (preferably without opening an actual text editor application, as this would clutter my workspace) and just paste that line in the Google Chrome browser.
In the last step of my script so far I do something causing message text to be output to Terminal. Then I get the text visible in Terminal to be copied to the clipboard as follows:
tell application "Terminal"
tell front window
set the clipboard to contents of selected tab as text
end tell
end tell
Now I can for example paste it, and it's something like
...
[I 15:03:31.259 LabApp] Serving notebooks from local directory: /workspace
[I 15:03:31.259 LabApp] The Jupyter Notebook is running at:
[I 15:03:31.259 LabApp] http://1fw5c518af9:1932/?token=5e6d97b348fsy734gd
[I 15:03:31.259 LabApp] or http://88.0.0.1:1932/?token=5e6d97b348fsy734gd
[I 23:56:47.798 LabApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 23:56:47.803 LabApp]
To access the notebook, open this file in a browser:
file:///root/.local/share/jupyter/runtime-open.html
Or copy and paste one of these URLs:
http://1fw5c518af9:1932/?token=5e6d97b348fsy734gd
or http://88.0.0.1:1932/?token=5e6d97b348fsy734gd
This always ends with text of the format or *URL*, e.g. in the above example it would be or http://88.0.0.1:1932/?token=5e6d97b348fsy734gd. This is separated from the line above by a line delimiter plus some trailing white-space before "or".
What I need to do is grab that URL, start a Google Chrome browser and paste it in there.
For opening Google Chrome, it should be simple enough, the following code (from this tut) takes you to Instagram:
tell application "Google Chrome" to activate
tell application "System Events"
key code 37 using command down
delay 0.5
keystroke "https://www.instagram.com/instagram"
delay 1
key code 36
delay 1
end tell
and literally all I need is something which edits what's on the clipboard to just the *URL* (in the case of the above example, just http://88.0.0.1:1932/?token=5e6d97b348fsy734gd). After that I can paste it from the clipboard (where Instagram is typed in, in the tutorial).
After trying the lovely answer by #user3439894 below I found the situation is a bit more complicated:
there are an unpredictable number of blank lines "" after the final
link.
I'm also wondering whether there may be white-space at the end
as well
I already know the form of http://88.0.0.1 (it's always consistently this) so is there a way of maybe searching for that and then just grabbing it with the rest of the link that follows? (it would be great to be able to delimit the end by either " " or new-line)
Edit 2:
In case http://88.0.0.1... occurs multiple times, we would like to select just one of these URLs - they are probably generally the same, but selecting the last would be safest.
What I need to do is grab that URL, start a Google Chrome browser and paste it in there.
&
This always ends with text of the format or *URL*, e.g. in the above
example it would be or http://88.0.0.1:1932/?token=5e6d97b348fsy734gd. This is separated
from the line above by a line delimiter plus some trailing white-space
before "or".
&
In case http://88.0.0.1... occurs multiple times, we would like to
select just one of these URLs - they are probably generally the
same, but selecting the last would be safest.
If what you are trying to do is get the last URL that starts with http://88 from the contents of the selected tab of the front window in Terminal, then here is a way to do it without using the clipboard, and open it in Google Chrome, and also do it without having to use UI Scripting.
In other words, no need to alter the text on the clipboard or keystroke the URL as you can just tell Google Chrome what to use for the URL.
Example AppleScript code:
tell application "Terminal" to ¬
set theTextFromTerminal to ¬
the contents of ¬
the selected tab of ¬
the front window ¬
as text
set theURL to ¬
the last paragraph of ¬
(do shell script ¬
"grep -o 'http://88.*$' <<< " & ¬
theTextFromTerminal's quoted form & ¬
"; exit 0")
if theURL is "" then return
if theURL does not start with ¬
"http://88." then return
tell application "Google Chrome"
activate
delay 1
if exists front window then
make new tab at ¬
end of front window ¬
with properties {URL:theURL}
else
set URL of ¬
the active tab of ¬
(make new window) to theURL
end if
end tell
Note: The example AppleScript code is just that and sans any included error handling does not contain any additional error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.
Related
I am working with Selenium on macOS to automate sending images using WhatsApp web in Google Chrome. The task involves uploading the image, and for that a system(Finder) prompt comes up to select the file. It's done in Windows using AutoIt.
I tried looking up how to automate this task in macOS, and I believe AppleScript can be used for it. Since I have no experience in GUI scripting, any help would be appreciated.
Thanks.
I was able to find the answer on another post on Stack Overflow. I have added the answer for anyone who comes across the same problem.
tell application "System Events"
keystroke "G" using {command down, shift down}
delay 1
keystroke "/path/to/file"
delay 1
keystroke return
delay 1
keystroke return
delay 1
end tell
I don't advocate GUI scripting any more than the burning down of the Amazon, but it seems to be necessary for this task, and I wanted to provide you with an example of a GUI script that tries its best to minimise the unpleasantness of the user experience, and aim for fewer weak points in the code where GUI scripts are most likely to falter.
If you know the path to your file—which I assume you do in these sorts of situations, as your script keystrokes the filepath—then you might find the following technique saves a few steps, and feels a bit more graceful in how it gets executed:
set filepath to "/path/to/image.jpg"
-- Copy file object to clipboard
set the clipboard to filepath as «class furl»
-- Make sure Chrome is in focus and the
-- active tab is a WhatsApp tab
tell application id "com.google.Chrome"
activate
if the URL of the active tab in the front window ¬
does not contain "web.whatsapp.com" then return
end tell
-- Paste the clipboard contents
-- and hit return (send)
tell application id "com.apple.SystemEvents"
tell (process 1 where it is frontmost) to tell ¬
menu bar 1 to tell menu bar item "Edit" to tell ¬
menu 1 to tell menu item "Paste" to set Paste to it
if (click Paste) = Paste then keystroke return
end tell
The if (click Paste) = Paste check should negate the need for a delay, as it explicitly forces AppleScript to evaluate the click command before going on to issue a keystroke. However, I can't test this under all possible conditions, and if there are other factors, like CPU usage, or process freezes, that are likely to give the script a chance to jump ahead, then just insert a small delay after then and move keystroke return down onto its own line.
If you wish to remove the file object from the clipboard afterwards, then simply add as the final line set the clipboard to (and just leave it blank after the word "to", which will clear the clipboard's contents). Of course, this won't affect any clipboard history data you might have if you use a clipboard managing app, only the system clipboard's current item.
I am trying to put the user search word into the url but it keeps thinking that the variable I have is the thing that I want to search...
set v to text returned of result
tell application "Google Chrome" to open
location"https://www.google.co.in/search?q=v"
How do I make sure it knows that v is a variable and not part of the url?
You have to concatenate the strings with the & operator:
"https://www.google.co.in/search?q=" & v
Be aware that you have to add percent escaping if v contains space characters.
You ought not to use open location, which actually opens a URL in the system's default browser, regardless of which application you send the command to. That's ok if your defaul browser is Chrome, but in that case, you can omit tell application "Google Chrome" to.
A more robust method is this:
set v to the text returned of the result
tell application "Google Chrome"
activate
if the number of windows is 0 then make new window
tell the front window to make new tab ¬
with properties ¬
{URL:"https://www.google.co.in/search?q=" & v}
end tell
Thankfully, using AppleScript version "2.7", on macOS "10.13.4", and Chrome "67" (and possibly earlier versions of any of these), you don't need to percent encode your string (v) to cater for spaces—this gets done automatically (but not for other special characters).
I use firefox for a long time as my only browser on Pc or Mac.
In a few words my problem: I want to create a service on mac with automator and
Applescript for quite instant translation using translate.google.com.
What works great with Safari or Chrome (below the 4 or 5 lines of script)
On run {input, parameters}
Tell application "Safari"
activate
try
Open location "https://translate.google.com/#auto/en/" & (the clipboard)
end try
end tell
end run
The same thing (script) does not work at all with Firefox, I try by different ways
To circumvent the impossible problem
On run {input, parameters}
Set theProcess to "Firefox"
Set info to {}
Set y to 0
Set x to 0
Set n to 0
Tell application "Applications / Firefox.app"
activate
Open location "http://translate.google.com/#auto/en/"
end tell
Tell application "System events"
Repeat with theProcess in (process "Firefox")
try
Set info to info & (value of (first attribute whose name is "AXWindows") of theProcess)
end try
end repeats
Set n to count of info
info
end tell
Tell application "System Events" to tell process "Firefox"
Set x to "1"
Set frontmost to true
try
Click menu item "Paste" of menu "Edit" of menu bar 1
end try
Repeat while x is "1" -
If x is "1" then
Keystroke "V" using command down
Set x to "0"
end if
end repeat
end tell
end run
By copying and pasting, the actions take place before the complete loading of the page, even by slowing down the Copy and Paste procedure.
After many observations there is a problem of formatting the text contained in the clipboard with the association of the URL, I improved this but it is not perfect yet.
tell application "Applications/Firefox.app" to activate
tell application "System Events" to tell process "Firefox"
set frontmost to true
set sentence to text of (the clipboard)
set thesentences to paragraphs of sentence
set thenewsentences to thesentences as string
set the clipboard to thenewsentences
keystroke "t" using command down
keystroke "https://translate.google.com/#auto/fr/" & (the clipboard) & return
end tell
Anyway if it works with Safari without modifying anything, the problem is at the Firefox entry, so if you can look at this problem, that would be very useful to us all.
Thank you for your attention.
Thank you for your answers.
Safari and Chrome perform the necessary encoding of reserved characters in the URL for you, but Firefox doesn't.
Therefore, you need to perform the encoding of the query-string value (the text to embed in the URL) explicitly.
The easiest (though not obvious) approach is to use perl, via a shell command, gratefully adapted from here:
# Example input that contains chars. that have special meaning in a URL ('&' and '?')
set the clipboard to "Non, Je ne regrette rien & rien ne va plus?"
# Get text from the clipboard and URL-encode it.
set encodedText to do shell script ¬
"perl -MURI::Escape -lne 'print uri_escape($_)' <<<" & quoted form of (the clipboard)
# Now it's safe to append the encoded text to the URL template.
tell application "Firefox"
activate
open location "https://translate.google.com/#auto/en/" & encodedText
end tell
The above approach works with all three browsers mentioned: Firefox, Safari, and Google Chrome.
Note:
As of (at least) Firefox v50, Firefox opens the URL in in a new tab in the current front window by default.
You can make Firefox open the URL in a new window instead, by unchecking Open new windows in a new tab instead on the General tab of Firefox's preferences.
Note, however, that this is a persistent setting that affects all URLs opened from outside of Firefox.
For an ad-hoc solution for opening in a new window that doesn't rely on changing the setting, see this answer of mine.
Hello below the service Automator with some version it is possible to encounter problems, I modified the script so that it works almost everywhere.
A frequent system error is the permission to applications to control your computer that is handled by the system preferences tab Security and Privacy, the system asks if you allow Firefox, TexEdit and others using this service for its keyboard shortcuts.
Also in Automator create service (to be General (and appear in all applications) no entry (up to Yosemite since El Capitan I saw that with Firefox for example all the services are usable), choose Execute a script Applescript paste the script below divided into 2 script or 1 script only.
on run
set Sn to ""
tell application "System Events"
set Sn to the short name of first process whose frontmost is true --here we look for and find which application to launch the service
tell process Sn
set frontmost to true
try
click menu item "Copy" of menu "Edit" of menu bar 1 -- there is used the Copier of the menu Editing of the application
end try
end tell
end tell
return the clipboard
end run
In the script following the entry is done with the contents of the Clipboard
On run {input}
on run {input}
set input to (the clipboard) -- Here we paste the contents of the Clipboard into a variable
try
set input to do shell script "Perl -MURI :: Escape -lne 'print uri_escape ($ _)' <<< " & quoted form of input --To format the text to make it usable with Firefox and the url of translate.google.com
tell application id "org.mozilla.firefox"
activate
open location "https://translate.google.com/#auto/en/" & input --here since version 50 of Firefox you must open a tab and not a new url window of translate.google.com, with option #auto automatic detection by google of the language, and fr to translate into French (these options are modifiable at will)
end tell
end try
end run -- end of the operation you have a tab open on translate, a text to translate and a translated text
I am writing some text in to word file i want to change the color of that text any one can help on that one plz.
I want to print the 'message' from following script in red color.
Here is the Script:
set message to "mostly these windows are popup in application"
on ResultCreationFuction(message)
try
set text_to_save to message as text
tell application "System Events"
tell application "Finder"
set sortedList to sort (get files of folder "SofTestAutomationResult" of desktop) by modification date
set FileCount to get count of sortedList
set theFile to (item FileCount of sortedList) as alias
end tell
set file_ref to open for access theFile with write permission
write (text_to_save & return) to the file_ref starting at eof
close access file_ref
delay 2
end tell
end try
end ResultCreationFuction
Some Details:
The file is word which is all ready present on above location having name "10.012.2014_17_4_20.doc" (the name of .doc file is not fix)
What you are attempting is the wrong way to do it.
To manipulate content like that, including formatted text (not plain
text), you need to work within, ideally, a well-scriptable app, like
Pages (or Word, perhaps, but I don't have that on the machine I'm
writing this from).
Don't use System Events if you don't need to. Use the apps with the appropriate AppleEvents/dictionary, etc. If you don't know what I'm talking about, you need to take advantage of the infinite resource known as the web.
"Fuction" is just bad form.
I would suggest doing a lot more reading up on how AppleScript works (or scripting in general), but to start you out, here is a script I just wrote in pages which sets the color of a specific word of the open document after putting text in there:
tell application "Pages"
set body text of document 1 to "hello there mister fancy pants"
set color of word 3 of body text of page 1 of document 1 to {64614, 0, 111}
end tell
If you have Pages, try this by starting with a blank page and running this script. Obviously, you could get rid of "word 3 of" in the 2nd line, and the whole body text will be red.
I hope this makes sense and is of help.
[edit]
I should mention that even TextEdit is scriptable and can open Word documents. Here's an example using TextEdit:
tell application "TextEdit"
set text of document 1 to "hello mister fancy pants"
set color of words 2 thru 3 of text of document 1 to {65535, 0, 0}
end tell
There is a little danger of non-Word apps losing formatting of Word files. But it just seems you are attempting something very simple, and I'm not sure if Word is really necessary here.
You can't add color using the write to eof. You should open the document in Word and then insert the line and add the color. Here's a script that should demonstrate how:
set text_to_add to "mostly these windows are popup in application"
set theFile to ((path to desktop folder) & "10.012.2014_17_4_20.doc") as string
tell application "Microsoft Word"
set theFile to theFile as string -- assuming theFile is an alias or :: path
open file theFile
tell active document
set endOfDoc to end of content of text object -- insert the text to end of document
set theRange to create range start (endOfDoc - 1) end endOfDoc
insert text text_to_add at theRange
set myRange to create range start endOfDoc end (endOfDoc + (length of text_to_add))
set color index of font object of myRange to red
save
end tell
end tell
I need to open multiple Safari (or open the tab is OK) based on the read result.
For example, if a file has
http://a.com
http://b.com
I want to open a.com and b.com using Safari.
How can I do that with Mac/AppleScript?
Maybe I can run python calling "open -a Safari "http://a.com", but I guess AppleScript is the tool for this kind of job.
not sure about python but this will read a text file and open windows let me see if I can get tabs for you though
set locations to paragraphs of (read (choose file with prompt "Pick text file containing urls"))
repeat with aline in locations
if length of aline is greater than 0 then
tell application "Safari"
make new document at end of documents
set URL of document 1 to aline
end tell
end if
end repeat
EDIT:
Ok this is better and it opens them in tabs of a single window
set locations to paragraphs of (read (choose file with prompt "Pick text file containing urls"))
tell application "Safari"
activate
set adoc to make new document
end tell
repeat with aline in locations
if length of aline is greater than 0 then
tell application "Safari" to make new tab at end of window 1 with properties {URL:aline}
end if
end repeat
New Addtion
this is yet another way based on regulus6633's post in conjunction with mine
set locations to paragraphs of (read (choose file with prompt "Pick text file containing urls"))
repeat with aLocation in locations
tell application "Safari" to open location aLocation
end repeat
If you want it to specifically open the links in Safari then mcgrailm's solution is good. However, you don't need the Finder for the first part so take that code out of the Finder tell block. There's no need to tell the Finder to do something that applescript can do itself.
However, you probably want to open the links in whatever browser is the user's default browser. It may be Safari or Firefox etc. You can do that with the "open location" command. So something like this is probably what you want...
set theFile to choose file with prompt "Pick text file containing urls"
set locations to paragraphs of (read theFile)
repeat with aLocation in locations
try
open location aLocation
end try
end repeat