How To Insert Variable Into JavaScript Action

I have a macro that downsizes images pasted into KM forum posts at the time of editing. Here it is:

I've highlighted a portion of text in that image; the value 650. I'd like to subtitute that value with a KM variable that one can set beforehand, but can't see a way to do this given that the text script editing field is one of the few types of input fields in KM that doesn't process text tokens.

Does anyone have a solution for this ?

Can you write the text to a file and then execute the text-file as a script.

1 Like

A tmp file...? Nice idea. I think that sounds like a solid workaround.

See Execute a JavaScript in Browser actions

Is there some reason this would not work:

var imageSizeStr = 'l' + document.kmvar.ImageSizeStr + 'x';
return "!["  + p1 + imageSizeStr // + the rest of this line
1 Like

Perfect. Thanks for pointing me to the relevant documentation. I missed that entirely, and didn't know one can retrieve KM variables through the browser in this manner. Many thanks.

1 Like

i have a variable (set as a parameter of the function) that is actually a function I want to run in chrome.

how do I insert it into KM such that it actually runs it like a function in KM

Really looking forward to your help here.
Thanks.

See Execute a JavaScript in Browser actions for an example.

But I don't understand your script -- it makes no sense to me since the function() statement is NOT valid. It would need to be something like this:

function schedule(pField,pNum) {
  frm.sxyz.value = pField;
  frm.sNum.value = pNum;
  frm.submit();
}

schedule('xyz', 222);

But even then, the JavaScript variable "frm" is undefined, so it will fail.
You need to get a reference to "frm", perhaps using document.querySelector()
But it is hard to say without knowing more details, including the HTML of the target web page.

As described in the Execute a JavaScript in Google Chrome documentation (which you can get to from the Help menu in the action (gear) :gear: menu), the Keyboard Maestro variables are available to the script as:

document.kmvar.schedule_command

This is plain text in the variable, so you will need to run the command - I don't know how to do that I'm afraid. eval maybe? Alternatively, you could do something like:

  • Set variable schedule_param1 to “xyz”
  • Set variable schedule_param2 to “222”
  • Execute script:
    • frm.sxyz.value = document.kmvar.schedule_param1;
    • frm.sNum.value = document.kmvar.schedule_param2;
    • frm.submit();

Something like that.

1 Like

Exactly what I was looking for.
followed your way of sending param1 and param2.
Thanks a lot!

Yup that's right. Sorry truncated the function a little because I thought that wasn't right.

Followed @peternlewis 's advice and got it working with param1, param2.

Thanks for the help!
Really appreciate it!