How to add an event listener to an Designer Extension?

I’m trying to write a designer extension that allows users to insert a form anywhere on a site. I haven’t been able to figure out how to add any kind of event listener. How can I listen to an onSubmit or onChange event?

Here’s my code so far:

document.getElementById('lorem').onsubmit = async (event) => {
  event.preventDefault();
  const element = await webflow.getSelectedElement();

  if (!element) {
    alert('element not found');
    return;
  }

  if (!element.save) {
    alert('element.save not found');
    return;
  }

  const input = webflow.createDOM('input');
  input.setAttribute('type', 'text');
  input.setAttribute('placeholder', 'calculate square root');
  input.setAttribute('id', 'square-root');
  input.setAttribute('onchange', 'foo'); // doesn't get saved in the DOM

  input.addEventListener('input', (event) => { // throw an error Property 'addEventListener' does not exist on type 'DOMElement'.
    const { value } = event.target;
    const number = Number(value);
    if (isNaN(number)) {
      return;
    }
    event.target.value = Math.sqrt(number).toString();
  });

  element.setChildren([input]);

  await element.save();
};

Also - how does one do type narrowing here? I keep getting TS errors that this or that method is not available on a given type.

update:
The addEventListener method is throwing an error, because input isn’t actually a proper dom node, but some kind of webflow object. document in this context isn’t my website, but actually the extension’s document. Since it’s rendered as an iframe I tried to access the parent document so that I can do DOM operations, but I got an XSS error message since the iframe is on a different domain than the website.

image

Hey Boris!

Are you trying to add the event listeners to the form for on the published site, or while users are in your App in the Designer? I.e. adding the event listener function to a input inside your App?

I don’t believe it is possible to use addEventListener for elements on the canvas using our Designer. You would have to do this by registering a script or adding a element that links to an external js file with those functions.

Do you have a bit more info about what you’re trying to achieve?