MacOSX:获得最重要的窗口标题

时间:2011-03-13 20:35:24

标签: macos applescript

我正在使用此代码获取窗口标题:

tell application "System Events"
    set frontApp to name of first application process whose frontmost is true
end tell

tell application frontApp
    set window_name to name of front window
end tell

但是,在某些情况下会失败。显然,当没有打开的窗口时它会失败,但那是好的。但是,在某些情况下,例如Texmaker,它会失败并显示错误。它也不适用于预览。

无论如何,即使是像Texmaker这样的案例,什么方法才能获得窗口标题?

4 个答案:

答案 0 :(得分:18)

这似乎始终有效:

global frontApp, frontAppName, windowTitle

set windowTitle to ""
tell application "System Events"
    set frontApp to first application process whose frontmost is true
    set frontAppName to name of frontApp
    tell process frontAppName
        tell (1st window whose value of attribute "AXMain" is true)
            set windowTitle to value of attribute "AXTitle"
        end tell
    end tell
end tell

return {frontAppName, windowTitle}

here获得了这个想法。

答案 1 :(得分:4)

根据艾伯特的回答,我做了

global frontApp, frontAppName, windowTitle

set windowTitle to ""
tell application "System Events"
    set frontApp to first application process whose frontmost is true
    set frontAppName to name of frontApp
    set windowTitle to "no window"
    tell process frontAppName
        if exists (1st window whose value of attribute "AXMain" is true) then
            tell (1st window whose value of attribute "AXMain" is true)
                set windowTitle to value of attribute "AXTitle"
            end tell
        end if
    end tell
end tell

return {frontAppName, windowTitle}

这是一个黑客,我没有经验,但优点是,如果没有窗口,它不会崩溃。

答案 2 :(得分:2)

尝试使用以下脚本:

tell application "System Events"
    set window_name to name of first window of (first application process whose frontmost is true)
end tell

我还没有确认它适用于TextMaker。

答案 3 :(得分:2)

这是基于 this script 的 jxa 中的替代版本。如果是普通浏览器,则包括窗口的 URL。

var seApp     = Application("System Events");
var oProcess  = seApp.processes.whose({frontmost: true})[0];
var appName   = oProcess.displayedName();

var url;
var title;

switch(appName) {
  case "Safari":
    url = Application(appName).documents[0].url();
    title = Application(appName).documents[0].name();
    break;
  case "Google Chrome", "Google Chrome Canary", "Chromium":
    url = Application(appName).windows[0].activeTab().url();
    title = Application(appName).windows[0].activeTab().name();
    break;
  default:
    title = oProcess.
      windows().
      find(w => w.attributes.byName("AXMain").value() === true).
      attributes.
      byName("AXTitle").
      value()
}

JSON.stringify({
  appname: appName,
  url: url,
  title: title
});

您可以通过 osascript -l JavaScript ./script.jxa

在命令行上运行它