Execute Javascript function in Chrome - giving errors

Hi everyone!

I'm struggling with executing JavaScript in Chrome using "Execute JavaScript in Front Browser" action. I've tried to call a simple function (window.updateSelection('right')), but consistently get errors like Uncaught TypeError or ReferenceError, indicating the function is not defined, even though it's in the global scope. The function works fine manually via the console.

Here's what I've tried:

  • Verified permissions: "Allow JavaScript from Apple Events" in Chrome is on.
  • Tested with delays to ensure the page is fully loaded.
  • Confirmed KM is executing commands via console.log.
  • Executed inline JavaScript successfully, but it doesn't persist beyond one action.
  • I saw a similar issue on the forums suggesting problematic variables in KM could be the cause. I checked and they're all clean.

Would anyone have insight into why the function works manually in the console but fails when triggered by KM? Any help would be greatly appreciated!


Here's what my console is telling me. I'm not an expert with this stuff, but this undefined looks like the culprit to me. Where is that coming from?

(Green highlight is my manual function trigger inside the console. Red is what's coming from KM)

And here's my macro. I've tried all options in here, All/No Vars, turning Modern Syntax off.
And what's up with this 9999 that gets sent when All Vars is enabled? I have deleted out all my previous variables in KM's Prefs / Variables, so I'm guessing this is built-in stuff.
KM JS

See: EditContext - Web APIs | MDN

It looks as if the .updateSelection method which you are hoping to use is provided by an EditContext API which may not be universally available.

It's clearly not defined, in the context in which you are evaluating that code, for the window object.

Hmm, do you mind explaining a bit more on this?

I'm running a super basic html test at this point.
Here's what it all looks like, from left to right: KM, HTML, Chrome, ChromeConsole

(KM is being triggered by StreamDeck)

What is 'left'?

updateSelection()'s web page says that it takes two parameters and throws a TypeError if there is only one. And if I squint I can see a TypeError...

OK - I just removed the parameter from the function altogether, so it's just updateSelection()

I think I must be missing something basic here. I haven't touched this web and JS stuff in years and it's evolved quite a bit! Any clues?

It still isn't a valid function because it doesn't have two, numeric, parameters.

Let's start from the beginning. What are you trying to achieve? Because updateSelection() appears to be all about "editable text context" -- presumably like this box I'm typing in now -- and all you have is buttons.

Ooh you're saying it needs to have 2 params?? easy peasy haha.

I'm just trying to make a 3 button menu that can be navigated with the StreamDeck: Press "Left", it moves the selection left. Press "Right", it moves right. Press "Go" and it hits the selected button

It's for my mum with dementia, I'm making her a custom interface that plays films, music, makes video calls. I've got all that stuff mostly working, this HTML part is just the visual feedback that helps guide her on what buttons to press on the StreamDeck.

I got chatGPT to throw the html/js code together. It works perfectly with the mac keyboard (not via KM but directly into chrome). But when triggered from KM it's throwing these errors.

I don't know what you mean about editable text context. Because it really shouldn't be that. It should just be mimicking the two L/R arrow keyboard buttons.

I just tried giving it two parameters:

Never a good idea :slight_smile:


See the functionality column in these benchmark test results:

Wolfram LLM Benchmarking Project

haha i was waiting for that one.
I mean, hard to go wrong with that code I'm looking at. Are there any flaws that you notice? Weird characters?

No -- the web page I pointed you to that documents the function you are trying to use says that it does:

Syntax

updateSelection(start, end)

Parameters
start
A number representing the new selection start.

end
A number representing the new selection end.

If the start and end values are the same, the selection is equivalent to a caret.

Exceptions
If only one argument is provided, a TypeError DOMException is thrown.
If either argument is not a positive number, a DOMException is thrown.
If start is greater than end, a DOMException is thrown.

Apart from you using completely the wrong function?

I'm a little confused. Is this the start of something bigger? Otherwise, you've got a three button menu and you're using three SD buttons to control it -- you could just use one SD button per option.

It probably isn't actually working -- it's your L/R arrows moving focus to the previous/next interface element. Have you tried just sending key strokes from the SD with the "Hotkey" option, or firing a KM macro that simulates the keystrokes?

It'll be doable with JS, but the above will be easier and will at least get you going for now.

Yes. It doesn't work.

Neither the semantics nor the context are correct.

Gotcha! updateSelection() is an existing function.
Ok so I changed it, still getting same error.

Roger

Yep it is. This is my first test before I create a series of navigation pages that can be controlled by the streamdeck. Once that's done, I'll have a whole entertainment/communication system that's running on her TV that can be entirely controlled via the stream deck (no keyboard / mouse), complete with visual feedback on screen.

Thing is, in trying to debug this thing I've taken all that functionality away. The code you're seeing has all that other stuff stripped out. It's just a tiny 1 line function, now called bumwiggle()

Just to put it more into context with the original objective I described, here's the original test with the updated function names. Hope this helps avoid confusion.

Thanks for the help by the way!

First 3 actions are triggered via keyboard directly in the browser window. The next 3 are triggered via KM JS: window.bumwiggle("left");

KM JS debugging

Here's the code

<script>
  window.onload = function() {
   
    setTimeout(() => {
     
      let options = ["comedy", "thrillers", "nature"];
      let currentIndex = 0;

      document.getElementById(options[currentIndex]).classList.add("highlighted");

      function bumwiggle(direction) {
        console.log(`Called bumwiggle with direction: ${direction}`);
        document.getElementById(options[currentIndex]).classList.remove("highlighted");

        if (direction === "left") {
          currentIndex = (currentIndex - 1 + options.length) % options.length;
        } else if (direction === "right") {
          currentIndex = (currentIndex + 1) % options.length;
        }

        document.getElementById(options[currentIndex]).classList.add("highlighted");
        console.log(`Added highlight to: ${options[currentIndex]}`);
      }

      function selectTheBugger() {
        console.log(`Called selectTheBugger. Selected: ${options[currentIndex]}`);
        alert("Selected: " + options[currentIndex]);
      }

      document.addEventListener("keydown", function(event) {
        if (event.key === "ArrowLeft") {
          console.log("ArrowLeft pressed");
          bumwiggle("left");
        } else if (event.key === "ArrowRight") {
          console.log("ArrowRight pressed");
          bumwiggle("right");
        } else if (event.key === "Enter") {
          console.log("Enter key pressed");
          selectTheBugger();
        }
      });

      window.bumwiggle = bumwiggle;
      window.selectTheBugger = selectTheBugger;
    }, 1000); 
  };
</script>

OK - This was the workaround solution all along!
No idea why I was fixating on KM executing the JS instead of just replicating keystrokes. Urgh. I'm probably following mother's footsteps.

This is now working with KM:
KM working

Still, I'll never know why KM executing the JS functions didn't work. But I'll do my best to avoid that method in the future lol

Thank you for helping out and following my commentary. :pray:

I'm back.

Completely different area of the "app" I'm making, but same issue as before in terms of Chrome giving errors when KM calls a JS function. I can't think of a way around it this time, so i'm hitting a brick wall. I've searched the forum to no avail.

Any ideas why the function loadIframexxx() isn't getting called?

HTML

<script>
    window.loadIframexxx = function(url) {
   	console.log('loadIframe called with URL:', url);
        document.getElementById('myIframe').src = url;
    }
    window.onload = function() {
	loadIframexxx("youtube_playlist.php?id=XYZ");  // this works
};
</script>

KM

execute javascript in Google Chrome:
window.loadIframexxx('youtube_playlist.php?id=xyz')


Chrome Console

VM1407:5 Uncaught TypeError: window.loadIframexxx is not a function at <anonymous>:5:8 at <anonymous>:6:4

clicking on the error code shows this:

(function () { 
 var kmvar = { 
 "Channel_PlaylistID" : "xyz", 
} 
loadIframexxx('youtube_playlist.php?id=xyz')
 })()

(pls ignore the xyz placeholder, and the fact that Channel_PlaylistID is being passed as a variable - i'm simplifying for the purposes of this post)