Chrome's support for AppleScript buggy or why does it mix up which window that has focus?

30 Views Asked by At

I have an AppleScript (AS) that opens two windows in Chrome, one normal and one in incognito mode (because some things need each type of window). The whole script performs in an infinite loop. Here is a simplified version:

on run {}
    tell application "Google Chrome"
        launch
        repeat
                set activeTab to 1
                my openURLS(URLs) -- in incognito window
                my generateData() -- in normal window

Opens multiple URLs/tabs in an incognito window

on openURLS(URLs)
    tell application id "com.google.chrome" to tell (make new window with properties {mode:"incognito"})
        repeat with theUrl in URLs
            set newTab to make new tab with properties {URL:theUrl}
        end repeat
    tell application "Google Chrome" to set active tab index of first window to 1

Opens myURL in a normal window, performs some actions and then closes this window, or, that is at least the goal.

on generateData()
    tell application "Google Chrome"
        make new window with properties {mode:"normal"}
        -- I thought my problem might be some timing issue. The following lines
        -- is an attempt to handle that, but the while-statement is never true
        repeat while mode of front window is not "normal"
            log ("front window is incognito")
            delay 0.1
        end repeat
        open location myURL
        get windows -- Is this necessary? I copied it from somewhere.
        repeat until (loading of active tab of window 1 is false)
            delay 1
        end repeat


    -- however, the if on the following line regularly, but not frequently
    -- (maybe 1 out of 30 loops), is true. So despite that I just created
    -- a "normal" window and then intends to open myURL in that window, 
    -- myURL from time to time is opened in an incognito-window!?!?
        if ((mode of window 1 = "incognito") and (URL of active tab of front window is equal to myURL) then 
        -- the next line works, it closes the tab with myURL in the incognito window!?!?
            close active tab of window 1 -- there is only one tab so this closes the window

As I mentioned above, most of the times/loops myURL is opened in a normal window, and the script finishes as expected, but regularly a normal window is opened but myURL is opened in the incognito window previously opened by the openURLS-handler above. When the script has been running for an hour or so I typically find 10-20 completely empty normal windows (empty as in they just display the "welcome screen" and the tab name is "New tab") that are "leftovers" from when Chrome opens myURL in the wrong window.

Is Chrome and its window handling buggy or what is this about? How can I workaround this problem? It is hard to debug since it happens, seemingly, randomly.

0

There are 0 best solutions below