Exception in template helper: TypeError: Cannot read property 'click' of undefined

Hello i am trying to automate rocketchat SSO screen by using this simple code:

document.getElementsByClassName(“rc-button rc-button–secondary external-login keyclock”)[0].click();

I am geting Exception in template helper: TypeError: Cannot read property ‘click’ of undefined

I am really novice when it comes to html,css,js frontend in general . From a google search i found out that my script is being executed before the DOM elements load which makes sense.

I found really hard to find a working solution to such a simple task .It’s a bit more tricky because this is runned on rocketchat administration scripts area.

Any ideas?

Hello dkwid,

It looks like your JavaScript code is valid. The code snippet below worked for me and I was able to print “click” in the console every time a button with classes “rc-button rc-button–secondary external-login keyclock” was clicked.

<!DOCTYPE html>
<html lang="en">
	<body>
		<button class="rc-button rc-button–secondary external-login keyclock" onclick="console.log('click');">Click Me!</button>
	</body>
	<script>
		document.getElementsByClassName("rc-button rc-button–secondary external-login keyclock")[0].click();
	</script>
</html>

So your problem seems to be that no HTML element with classes “rc-button rc-button–secondary external-login keyclock” exist at the time you run this JavaScript code.

I see 2 possible reasons for your error message:

  1. Assuming you’re in a Blaze template, you run your JavaScript code in the onCreated event - at that point, your template hasn’t been rendered yet and the HTML doesn’t exist yet. Try running the same code in the onRendered event.

  2. The HTML element just doesn’t exist yet. If your rocketchat widget loads from an external source, it may load a few seconds after your Meteor page is rendered, which would explain why the HTML element isn’t there. You could run your JS code with setTimeout or find another way to delay it.

Good luck!

1 Like

I would second @yacinemerzouk answer, but to add to it…have you tried putting the HTML in a child template and firing the JavaScript there? You would want to add the script in the onRendered lifecycle method.

If the script is in a child component, then it will fire only once the child has been rendered. This is fairly typical behavior for Blaze, and is something you will likely run into quite a bit. Essentially if you have an element that has init scripts (jQuery and the likes) that look for really ANY DOM element, it should be in a child component. This will save you worlds of pain later :slight_smile: