batman
batman

Reputation: 3685

Activate the frontmost Safari and run Javascript

I'm trying to run Javascript on the Safari, whose frontmost is true.

tell (application "Safari" whose frontmost is true) to do JavaScript theScript in current tab of first window

But I get an error like this:

execution error: Can’t get application "System Events" whose frontmost of it = true. Access not allowed. (-1723)

where I'm making mistake?

Upvotes: 1

Views: 536

Answers (1)

l'L'l
l'L'l

Reputation: 47169

AppleScript often requires the syntax be formatted in a specific way. In the case of your script it can't differentiate identifiers because you've placed them incorrectly on the same line.

set theScript to "alert('Hello, World!');"

tell application "Safari"
    set frontmost to true
    activate
    do JavaScript theScript in current tab of first window
end tell

You can test your script in AppleScript editor by compiling and running it. The events, replies and results should give you some indication of where problems might be.

EDIT: to deal with a process which is the frontmost (or most recent):*

set theApp to "Safari"
set theScript to "alert('Hello, World!');"

on isOpen(appName)
    tell application "System Events" to (name of processes) contains appName
end isOpen

set isActive to isOpen(theApp)
if isActive then
    tell application "System Events" to tell (process "Safari" whose frontmost is true)
        tell application "Safari"
            activate
            tell application "System Events" to set frontSafari to item 1 of (get name of processes whose frontmost is true)
            if (count windows) is 0 then
                display dialog "There are no " & theApp & " windows open." buttons {"OK"}
            else if frontSafari is "Safari" then
                tell application "Safari" to do JavaScript theScript in current tab of first window
            end if
        end tell
    end tell
else
    display dialog theApp & " is not currently running." buttons {"OK"}
end if

Upvotes: 2

Related Questions