Last active
December 8, 2023 22:53
-
-
Save logic2design/4ec1840adf4896a7c9b94c8a0f2587f8 to your computer and use it in GitHub Desktop.
This Applescript will open the first URL link on the page that matches a search value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
############################################################# | |
# Title: Find all URL Links on Webage then open link based on a Search value | |
############################################################# | |
#Iain Dunn | |
#https://www.logic2design.com | |
#https://twitter.com/Logic2Design | |
#[email protected] | |
############################################# | |
# Script | |
############################################# | |
use AppleScript version "2.4" | |
use framework "Foundation" | |
use scripting additions | |
### Nominated Website option | |
(* | |
set urlLink to "http://www.apple.com" | |
tell application "Safari" | |
set the URL of the front document to urlLink | |
delay 2 | |
set pageText to source of document 1 | |
end tell | |
*) | |
### Safari Front Window option | |
try | |
tell application "Safari" | |
set pageText to source of front document | |
end tell | |
set thelist to my findURLsIn:pageText | |
display dialog "What is the link keyword?" default answer "" | |
set seek to text returned of the result | |
set linkPosition to getPositionOfItemInList(seek, thelist) | |
set firstLink to item linkPosition of thelist | |
tell application "Safari" to set URL of front document to firstLink | |
on error | |
display dialog "The search value was not found" buttons {"OK"} default button "OK" | |
end try | |
################################################################################# | |
# Functions | |
################################################################################# | |
on findURLsIn:theString | |
set anNSString to current application's NSString's stringWithString:theString | |
set theNSDataDetector to current application's NSDataDetector's dataDetectorWithTypes:(current application's NSTextCheckingTypeLink) |error|:(missing value) | |
set theURLsNSArray to theNSDataDetector's matchesInString:theString options:0 range:{location:0, |length|:anNSString's |length|()} | |
return (theURLsNSArray's valueForKeyPath:"URL.absoluteString") as list | |
end findURLsIn: | |
on getPositionOfItemInList(theItem, thelist) | |
repeat with a from 1 to count of thelist | |
if item a of thelist contains theItem then return a | |
end repeat | |
return 0 | |
end getPositionOfItemInList |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment