Execute JavaScript in Browser Actions – Best Practices

The Keyboard Maestro wiki page:

actions:Execute a JavaScript in Browser [Keyboard Maestro Wiki]

(in the section Using Keyboard Maestro Variables)

Makes the following point:

:warning: Note that because your variables are passed to the web page, any other scripts running on that web page will have access them, and this could be a privacy issue if the information is misused by the web page.

This will typically not pose a problem, but if you are using these actions on pages where you might not want other scripts to be able the read the names and values of all your Keyboard Maestro variables, it's a sensible idea to clear the document.kmvar reference, as soon as you don't need it, by doing things like:

Prefacing the earliest line which no longer needs document.kmvar with a statement like:

document.kmvar = undefined

Or, if you are running more than one Execute JS action on the same page, and don't want one of them to delete document.kmvar before the other consults it, you could conclude the whole macro with a further action like:

It will also be good practice, if you make much use of these browser actions, to minimize the amount of information in documents.kmvar by maximizing your use of temporary Keyboard Maestro variables.

i.e. variables with instance or local prefixes. See under Instance variables in:

manual:Variables [Keyboard Maestro Wiki]


Alternatively, if you:

  • don't want a document.kmvar reference to be created in the website's DOM model at all, or
  • you are using multiple actions, launched at different moments, on the same page, and there is any risk of a value needed by one action having been changed by another,

and assuming that you do need run-time access, within your JS, to the values of Keyboard Maestro variable names, then you can bypass the use of the Execute a JS in Browser actions entirely, and run your code, with a private copy of the kmvar names and values for each action, inside a non-global JavaScript context to which other scripts have no access.

Here is one approach (wrapping the user JS in a private context, and executing it in the browser, with access to a private and temporary kmvar object, from JavaScript for Automation):

Examples for Safari and Chrome:

Safe JS in Safari and Chrome Macros.kmmacros (25.1 KB)