Search code examples
javascripthtmldomspecifications

When do custom elements invoke lifecycle hook formStateRestoreCallback with reason argument equal to "autocomplete"?


I tried to find examples where the formStateRestoreCallback lifecycle hook could return autocomplete as the second reason argument, but I didn't find anything.

Here is a quote from the specification:

When user agent updates a form-associated custom element's value on behalf of a user or as part of navigation, its formStateRestoreCallback is called, given the new state and a string indicating a reason, "autocomplete" or "restore", as arguments.

To get the reason with restore you just need to refresh the page with a certain custom element on the page (don't forget to use setFormValue)

customElements.define(
  "my-input",
  class extends HTMLElement {
    constructor() {
      super();
      this.internals_ = this.attachInternals();
      this.internals_.setFormValue("sendData", "localData");
    }
    static get formAssociated() {
      return true;
    }
    connectedCallback() {
      console.log("connectedCallback has been invoked");
    }
    formResetCallback() {
      console.log("formResetCallback has been invoked");
    }
    formStateRestoreCallback(state, mode){
      console.log("formStateRestoreCallback:", state, mode);
    }
  }
);

but what do you need to do to get autocomplete?

Does anyone know if this thing works?


Solution

  • In the same document, a bit later you can see the specs say

    If the user agent has a form-filling assist feature

    I suspect this means some kind of AT.

    Interestingly, WPT only checks that the property is visited, but not that the callback is ever called, not even with "restore".

    And none of the "big 3" browsers seem to have implemented the "autocomplete" when they did implement formStateRestoreCallback.

    This change implements form-associated custom elements as per spec [1], with exception of formStateRestoreCallback() being called for autofill and support of File interface for saving / restoring state.

    (emphasize mine)

    Firefox's has pretty much the same:

    Note that 'autocomplete' for custom elements remains unsupported.

    And in Chrome, while they do define the "autocomplete" mode, walking up the call hierarchy of CustomElementFormStateRestoreCallbackReaction(), we end up at a single, CustomElement::EnqueueFormStateRestoreCallback(Target(), restored_state,"restore") with an hardcoded "restore" mode, no "autocomplete" ever.

    Maybe other user agents do call it though. And for it to be called, you'd need to follow the same rules as for autocomplete to work: have your element with an name or id attribute, in a <form> with a submit button.