Задайте расширение Chrome с помощью AppleScript - PullRequest
2 голосов
/ 22 марта 2020

Я столкнулся с некоторым препятствием, и я мог бы использовать предложение. Часть сценария, который я пишу, нацелена на расширение в браузере Chrome, чтобы сделать снимок экрана всего сайта. Мне удалось идентифицировать элемент с помощью инспектора специальных возможностей, но я не могу понять, как щелкнуть этот элемент. Я попробовал несколько вариантов прилагаемого кода без особой удачи.

tell application "System Events"
tell process "Google Chrome"
    tell group "Extensions" of group "BBC - Homepage - Google Chrome" of window "BBC - Homepage - Google Chrome"
        click (first button where its accessibility description = "Full Page Screen Capture")
    end tell
end tell

end tell

, а также

tell application "System Events"
delay 1
tell process "Google Chrome"
    click UI element "Full Page Screen Capture" of group "Extensions" of group "BBC - Homepage - Google Chrome" of window "BBC - Homepage - Google Chrome"
end tell

end tell

Также: я могу настроить таргетинг на другие элементы в группе расширений (например, Window Resizer), но этот не хочет сотрудничать. enter image description here

Любое предложение будет приветствоваться. Заранее спасибо.

1 Ответ

1 голос
/ 23 марта 2020

Во-первых, мы открываем новую пустую вкладку в Google Chrome. Меньше элементов интерфейса хорошо для анализа. затем мы запускаем код (XXX) ниже:

tell application "Google Chrome"
    activate
    delay 0.3
end tell

tell application "System Events"
    tell front window of (first application process whose frontmost is true)
        set uiElems to entire contents
    end tell
end tell

Поиск "экран" в текстовом выводе, мы видим строку, как это:

кнопка "Полный захват экрана страницы" группы "Расширения" группы "Новая вкладка - Google Chrome" окна "Новая вкладка - Google Chrome" процесса приложения "Google Chrome",

Итак, мы знаем

кнопка в группе (Расширения),

группа (Ext ...) в группе (Новая вкладка ...),

группа (Новая вкладка ...) в окне ...

Итак, мы тестируем приведенный ниже код:

tell application "Google Chrome"
    activate
    delay 0.3
end tell

tell application "System Events"
    tell process "Google Chrome"
        tell window "New Tab - Google Chrome"
            tell group "New Tab - Google Chrome"
                tell group "Extensions"
                    tell button "Full Page Screen Capture"
                        click
                        --perform action "AXPress"
                    end tell
                end tell
            end tell
        end tell
    end tell
end tell

Работает. Но мы видим, что название активной вкладки «Новая вкладка - Google Chrome» находится в коде, поэтому, если мы go перейдем на другую вкладку, код не будет работать. Поэтому нам нужно знать, как получить название активной вкладки переднего окна. Я сделал много испытаний. Наконец я нахожу ответ на этой странице .

osascript -e 'tell app "google chrome" to get the title of the active tab of window 1'

Затем я помещаю его в свой AppleScript, проверяю код ниже:

tell application "Google Chrome"
    activate
    delay 0.3
end tell

tell application "System Events"
    tell process "Google Chrome"
        set theTitle to do shell script "osascript -e 'tell app \"google chrome\" to get the title of the active tab of window 1'" as text
        set theTitle to theTitle & " - Google Chrome"
        --note the example title is "New Tab - Google Chrome". Don't forget to attach " - Google Chrome"
        tell window theTitle
            tell group theTitle
                tell group "Extensions"
                    tell button "Full Page Screen Capture"
                        --click
                        perform action "AXPress"
                    end tell
                end tell
            end tell
        end tell
    end tell
end tell

Большую часть времени, эта версия кода работает, но иногда она не работает. Я запускаю код (XXX) на этой вкладке, интересно, имя кнопки изменилось с «Захват экрана на всю страницу» на «Захват экрана на всю страницу

Имеет доступ к этому сайту» Обратите внимание, он вставляет «\ r» после Слово «Захват». Итак, мы знаем, что заголовок окна может измениться, а имя кнопки может измениться. Поэтому я пытаюсь сделать обработчик. Проверьте код ниже:

use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions

tell application "Google Chrome"
    activate
    delay 0.3
end tell

try
    set buttonName to "Full Page Screen Capture"
    fullPageScreenshot(buttonName)
on error
    set buttonName to "Full Page Screen Capture
Has access to this site"
    --note here is a "\r"
    fullPageScreenshot(buttonName)
end try

on fullPageScreenshot(buttonName)
    tell application "System Events"
        tell process "Google Chrome"
            set theTitle to do shell script "osascript -e 'tell app \"google chrome\" to get the title of the active tab of window 1'" as text
            delay 0.2
            set theTitle to theTitle & " - Google Chrome"
            --note the example title is "New Tab - Google Chrome". Don't forget to attach " - Google Chrome"
            tell window theTitle
                tell group theTitle
                    tell group "Extensions"
                        tell button buttonName
                            --click
                            perform action "AXPress"
                        end tell
                    end tell
                end tell
            end tell
        end tell
    end tell
end fullPageScreenshot

Теперь этот код версии, я тестирую его более 20 раз, он всегда работает. Я не использую это расширение слишком часто. Моя версия Google Chrome - версия 80.0.3987.149 (официальная сборка) (64-разрядная версия); и MacOS 10.12.6. Пожалуйста, дайте мне знать, если этот код работает на вашем компьютере.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...