This script grabs the embed code from a YouTube video and pastes it into a MarsEdit blog post window. It does it by simulating a series of tab/copies until it reaches the text box containing the embed code. If the video can’t be embedded, YouTube displays “Embedding disabled by user request” where the embed code would normally be. In this case, the script throws up a dialog box asking to search for similar content.
tell application "Safari"
activate
set docNum to number of documents
if docNum is equal to 0 then
my searchTry()
else
set firstURL to URL of document 1
if firstURL contains "youtube.com/watch" = true then
tell application "System Events" to keystroke "l" using command down
repeat
set embedCode to do JavaScript "getSelection();" in document 1
if embedCode contains "<object" then
--paste embed code into MarsEdit, etc.
exit repeat
else
tell application "System Events"
tell process "Safari"
key down tab
delay 0.5
key up tab
end tell
tell application "Safari"
set noEmbed to do JavaScript "getSelection();" in document 1
if noEmbed contains "Embedding disabled" then
my similarTry()
exit repeat
end if
end tell
end tell
end if
tell application "Safari"
set pageTitle to name of document 1
set myTitle to (characters 11 thru end) of pageTitle as string
end tell
end repeat
else
my searchTry()
end if
end if
end tell
on searchTry()
--display a search dialog box to search YouTube, etc.
end searchTry
on similarTry()
--get similar YouTube content, etc.
end similarTry
This works great as long as YouTube is currently displaying in English. If, for instance, it is in German, “Embedding disabled by user request” will be “Einbetten auf Anfrage deaktiviert” - which will prevent the script from exiting the tab/copy loop (this is why I currently have the ˜delay 0.5’ command in the loop, which gives me a fighting chance to kill the script if it gets out of control - I’ve had to force shut down my MBP a few times when the loop ran wild…). (Here is a link to a video that can’t be embedded so you can see what I mean - Tangled Up in Blue)
Is there a way to exit a loop after a certain number of failed attempts? This way, even if it can’t find the embed code, it won’t crash the machine…
Thanks!
Peter.
p.s. - any other comments on the script would also be much appreciated.