I’m trying to make a simple JXA script — triggered by KM — to grab the URL of the frontmost safari tab so it can be used to create a Markdown link in iA Writer.
But it fails if the Safari window is on another virtual desktop or is fullscreen. I typically work with Safari and iA Writer fullscreen on adjacent desktops. There’s probably an obvious solution I’m missing (new to JXA) but I’ve been scratching my head about it for while.
It is odd. The AppleScript version outputs this error:
/var/folders/dm/7tn97pfn2tn05dvcsdhb6cl40000gn/T/Keyboard-Maestro-Script-E759A975-9686-40AD-8D1B-04D58E2F1DD4:60:98: execution error: Safari got an error: Can’t get tab 1 of window 1 whose visible = true. (-1728)
And the JXA version outputs this error:
/var/folders/dm/7tn97pfn2tn05dvcsdhb6cl40000gn/T/Keyboard-Maestro-Script-CAC4FBD6-C751-4BC7-8C31-95F15419CFC7:31:65: execution error: Error on line 2: Error: Can’t get object. (-1728)
When Safari is on the same desktop, I get exactly what I expect: the URL. The same thing happens if I run it the commands in the interactive osacript REPL. It works when the terminal is on the same desktop as Safari, and stops working when I move the terminal to a different desktop.
I’m using Safari Version 10.0.3 on Sierra 10.12.3 (MacBook Pro 13-inch with Touchbar)
The need for this script has largely been removed with KM 8+, which introducted all of the Front Browser Actions and Tokens. So to get the URL of the frontmost tab in the frontmost window of the Front Browser (if it is Safari or Chrome), then use this token: FrontBrowserURL token
Original Post
Unfortunately, Chrome uses a slightly different syntax, so the same statement, with a different app name, won't work for Chrome.
this is the best I could do to handle either Safari or Chrome.
Maybe you guys can do better.
var seApp = Application("System Events");
var oProcess = seApp.processes.whose({frontmost: true})[0];
var appName = oProcess.displayedName();
switch (appName) {
case "Safari":
var frontMostURL = Application("Safari").documents[0].url();
break;
case "Google Chrome":
var frontMostURL = Application("Google Chrome").windows[0].activeTab().url()
break;
}
frontMostURL
Since you are mentioning it, during my personal Windows episode (2007–2008) I discovered a a very nifty thing, called “AutoHotkey”. Funny thing is, – I knew KM/Automator before – but AutoHotKey really got me into Automation on the Mac. Let’s say, it showed me what can be done.