Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MacOSX: get foremost window title

I am using this code to get the window title:

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

However, this fails in some cases. Obviously it fails when there is no open window but that is Ok. However, in some cases, for example for Texmaker, it fails with an error. It also doesn't work for Preview.

What would be a way to get the window title anyway, even for cases like Texmaker?

like image 981
Albert Avatar asked Mar 13 '11 20:03

Albert


People also ask

What script does Apple use?

What Is AppleScript? AppleScript is a scripting language created by Apple. It allows users to directly control scriptable Macintosh applications, as well as parts of macOS itself.


2 Answers

Give the following script a try:

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

I haven't verified that it works for TextMaker, though.

like image 68
sakra Avatar answered Oct 20 '22 16:10

sakra


Here's an alternative version in jxa based off of this script. Includes the URL of the window if it's a common browser.

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
});

You can run this on the command line via osascript -l JavaScript ./script.jxa

like image 37
iloveitaly Avatar answered Oct 20 '22 16:10

iloveitaly