How to Identify Whether a Browser Script Is Running in KM or Not?

I have a number of scripts that may either be:

a) run in a browser console by people who do not have KM OR
b) run in a browser, triggered by KM

Depending on which it is, I'd like the JavaScript to do different actions sometimes.

For example, if it's triggered via KM I may want to handle the results in a certain way (show results in window) but for everyone else log to console.

Is there a bit of script that I can use in my JS that will achieve this? And critically, will not error when run in a browser by someone without KM?

kinda like:

if (kmEngine) {
//do KM things
} else {
//console.log things
}

Hey Lloyd,

This may give you a clue:

Execute JavaScript in Browser Actions – Best Practices

-Chris

Generally you can inspect the cast of characters in the global name-space.

If what you mean there is that the JS code is being evaluated from one of Keyboard Maestro's Execute JavaScript in Browser actions, then you can look for document.kmvars (though this document property persists, by default, after the action run is terminated).

This expression, for example, evaluates to a boolean value:

Object.getOwnPropertyNames(document).includes("kmvar")

or perhaps more efficiently:

Boolean(document.kmvar)

If the context which you wish to detect is that of a Custom HTML prompt, then this would suffice for a Bool on which your conditional evaluations could turn:

Boolean(KeyboardMaestro)

(though the previous expressions should also work, I think)

1 Like