Getting a value from Google Chrome console back into KM

I have some scripts (JavaScript) that I run in the browser console that are triggered by KM hotkeys. The output of the scripts is a console.log statement (or statements) that I then manually copy back out and paste into a text editor where I then need to do some cleaning up (because the console adds some extra text).

Is it possible to get what is logged in the console back into KM where I can then do some manipulation automatically?

The answer is found in

Add the following code before other js code

console.orgLog = console.log;

console.log = function(value)
{
    console.orgLog(value);
    window.captureLogStr = `${window.captureLogStr || ""}\n${value}`.trim();
};

and at the end of those js code, return window.captureLogStr

What not just put your scripts in a KM Execute a JavaScript in Front Browser action?

You can then set the return to a variable, Clipboard, or window.

Ah, that's what I was doing (but I was referencing an file rather than code directly in the KM window, so that the code can be source controlled etc). So my script just does some DOM traversal to retrieve some values and outputs in the console, but ideally I'd like that output back in KM for … things :slight_smile:

I only just realised that there is an option in there to handle the output.

So, is the first reply (with the script example) still needed?

I don't see a request for a script, and I don't need one.

So, let's say I wanted to interrogate a table and retrieve the data in the first column with JS:

var table = document.querySelector("table");
var trs = table.querySelectorAll("tbody tr");
var id="";
var allIds="";

Array.from(trs).forEach(tr => {
console.log(tr.querySelector("td:first-child"));
 id = tr.querySelector("td:first-child").textContent;
 allIds+=id+"\n";
});

console.log(allIds);

I just need to get that variable allIds back into KM. If I could see an example of how I capture that I'd really appreciate it. (or if you can confirm that the first reply here is doing that, that'd be great too).

Did you test your code?

I would use something like this:

var table = document.querySelector("table");
var trs = table.querySelectorAll("tbody tr");

var idList = Array.from(trs).map(function(e) {
  var id = e.querySelector("td:first-child");
  return id.innerText;
});

idList.join('\n');

Note that to return results outside of a function, just enter the variable name.
You don't need a console.log.

You may need to test my script in the Chrome JavaScript console.

Good luck and let us know if that works.

Yeah, the code was working fine, so the issue was not about the the JS, but rather how I then take what was output in the console back in to KM. That's the bit I wasn't clear on, but literally I just needed to type the variable at the end and that is the result that KM uses :slight_smile:

Thanks - I got it now.

1 Like