Bart Simpson
Bart Simpson

Reputation: 849

AppleScript: How to reload a Safari window without bring the window to the foreground while I am in other Desktop space

I want to write an AppleScript to achieve a simple task. That is, I open a Safari window on Desktop 1 and automatically reload the browser every 30 minutes while I do my daily work on Desktop 2.

Here is my script:

tell application "Safari"
    activate
    tell application "System Events"
        tell process "Safari"
            keystroke "r" using {command down}
        end tell
    end tell
end tell

This script works. However, whenever the script is executed, my current Desktop 2 will be brought back to Desktop 1. It is distracting to my workflow.

Is there any way to just let Safari to reload in the background without bring Safari window to foreground on Desktop 1?

I have done a couple of searches; many of them say I should not use "activate" in my script. I tried that but then the script will just do nothing.

Upvotes: 3

Views: 6215

Answers (1)

markhunte
markhunte

Reputation: 6932

You can simply get the URL of document 1, then tell Safari to set the URL of document 1 to that URL.

The effect is the page will reload. Without bringing Safari to the front or jumping to Safari while you are in another space.

    tell application "Safari"
    set docUrl to URL of document 1

    set URL of document 1 to docUrl
end tell

Also a simple on idle handler and saved as an Application (Stay open checked) that will run every 1 minute but not when Safari is fronmost. i.e when you are actually using it.

on idle

    set frontApp to name of application (path to frontmost application as text)

    if frontApp is not equal to "Safari" then
        tell application "Safari"
            set docUrl to URL of document 1

            set URL of document 1 to docUrl
        end tell

    end if
    return 60
end idle

Upvotes: 5

Related Questions