DEV Community

Cover image for Refilling custom dropdowns from a Chrome content script: MUI, Ant Design, Radix, react-select
Mohamed Sabbah
Mohamed Sabbah

Posted on Fully Autonomous

Refilling custom dropdowns from a Chrome content script: MUI, Ant Design, Radix, react-select

I made FormEcho to save answers from a web form and put them back when I needed the same form again. The ordinary text inputs were the straightforward part. A dropdown that looked ordinary could have a button, a search input, a hidden input, and a list of options mounted somewhere else in the document.

The useful distinction was between the element that displays an answer and the interaction that makes the application accept it. A native input can often be restored with a setter and events. A custom dropdown usually has to be opened, searched or navigated, and selected. You also need to check that it actually selected the answer you wanted.

Start with the native setter, but know where it stops

A plain assignment can make a text box look right without updating the state a React form uses. In particular, an assignment can go through the setter the framework is tracking. Dispatching an event afterward might then leave React seeing no change. The content script calls the platform setter from the appropriate prototype, rather than starting with the instance setter. This is the actual helper from the extension:

  function setNativeValue(el, value) {
    const proto = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : el.tagName === 'SELECT' ? HTMLSelectElement.prototype : HTMLInputElement.prototype;
    const desc = Object.getOwnPropertyDescriptor(proto, 'value');
    if (desc && desc.set) desc.set.call(el, value);
    else el.value = value;
  }
Enter fullscreen mode Exit fullscreen mode

The ordinary input path then dispatches bubbling input and change events. In a custom dropdown the same native setter can help type a search string, but it does not choose an item. A search box displaying “Ontario” and a widget actually having “Ontario” selected are two different states. For a combo, the script saves the selected labels and later looks for a matching option, rather than treating whatever was in the search input as the answer.

Material UI: ignore the hidden twin

A Material UI select can expose a visible control and also keep a native input around for form submission. Writing .value on the hidden input can change what you see in the inspector without updating the component. Saving both nodes is worse: the capture sees two fields where the person using the form sees one. On refill, one can be reported missing even when the visible answer was set correctly.

This is the filter from the field scan. It keeps the hidden twin out of the list before the script reads answers:

      if (el.tagName === 'INPUT' && el.getAttribute('aria-hidden') === 'true' && el.tabIndex === -1) continue;
Enter fullscreen mode Exit fullscreen mode

The visible control still needs the dropdown interaction. Open it, look through the visible options and pick the saved label. For related widgets such as an autocomplete, the actionable input can be smaller than the visible box around it, so the scan also considers whether the enclosing combo is visible. A rule that excludes every small input would miss some of the controls it was supposed to restore.

Ant Design: distinguish the search handle from a password field

The search handle in an Ant Design select can carry autocomplete="new-password" to keep browser suggestions out of the widget. I originally treated that attribute as reason enough to skip the input. That made a working privacy filter look like a dropdown compatibility problem. It also meant a plain .value assignment was the wrong repair: even if I reached the input, I would only be putting text into the filter box.

The capture code makes the autocomplete exception only after the element has been classified as a combo, and still checks its identifying attributes for sensitive names:

    if (SENSITIVE_AUTOCOMPLETE.test(ac) && kindOf(el) !== 'combo') return true;
    const hay = [el.getAttribute('name'), el.id, el.getAttribute('placeholder'), el.getAttribute('aria-label')].filter(Boolean).join(' ');
    return SENSITIVE_NAME.test(hay);
Enter fullscreen mode Exit fullscreen mode

The combo path opens the menu, types into an editable handle when there is one, and looks for the saved label. Ant Design option elements can be found through their option class as well as the standard option role. The separate selected-item display gives the script a better way to check the outcome than reading the search text back.

Radix: send the pointer sequence, including the release

A Radix select trigger can be a button. Assigning .value does not tell that trigger to open, and calling click() does not produce a pointer-down event. In the demos I tested, opening the list and then choosing an option required more than a lone click.

The shared helper dispatches pointer-down, mouse-down, pointer-up, mouse-up and click. The selection path also sends a separate release on the document before pressing the option. That release gives the opening guard a chance to clear so the first option press is not swallowed. Here is the order in the current code:

      hit.scrollIntoView?.({ block: 'nearest' });
      // Some libraries swallow the first pointer release after opening (a guard against accidental picks).
      el.ownerDocument.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, pointerId: 1, pointerType: 'mouse' }));
      press(hit);
      await sleep(160);
Enter fullscreen mode Exit fullscreen mode

The script checks the displayed value after the press. If it did not change and the option is still connected, it tries focusing the option and pressing Enter. The check matters more than whether the script managed to dispatch all the events. Dispatch is something the extension controls; accepting the choice is something the page controls.

react-select: look for a choice, not just an input

In react-select, the input you can type into is a handle for the menu. .value = savedAnswer can put a string into that handle without committing a selection. The script recognizes the familiar react-select input ID pattern as one signal that a combobox is a genuine select handle:

    if (el.getAttribute('role') !== 'combobox') return false;
    if (/^react-select-.+-input$/.test(el.id)) return true;
Enter fullscreen mode Exit fullscreen mode

That pattern helps classify a control, but it does not make the exact ID a durable record key. To find options the script first checks the list referred to by aria-controls or aria-owns. Otherwise it looks for visible options in the same document. That fallback matters when the menu is mounted apart from the control. Once the menu is open, the script searches where it can type, picks the option by displayed text, and checks the selected labels in the widget. It avoids toggling an option that is already selected during a multi-select refill.

The field you found can disappear

A form that shows state or province choices after a country change can replace the control while you work. The plain fields are written first, with the combos handled afterward. When a queued combo node is detached by the time its turn comes, the script searches the current DOM for the control again before trying to open it.

The stored description includes the kind of field, its name, label, placeholder, ARIA label, autocomplete token and position. A generated ID gets less weight than a stable one. A position-only fallback is allowed if the form still has the same field count and the candidate at that position is of the same kind. That narrows the fallback, but it cannot tell two truly indistinguishable controls apart after a reorder. This is a practical reason to report misses rather than say every refill worked.

For my own test cases, I treat a dropdown refill as successful only when the control reports the selected label after the menu closes. Seeing the search text appear or getting an option to highlight is not enough. A dependent control is another useful check: change the parent selection, let the new options render, then confirm the child control took the intended answer too.

On the public demo pages for Material UI, Ant Design, Radix and react-select, the script restored 12 of 12 dropdowns. On 20 ordinary public form pages it restored 128 of 129 fields. Those are results for those pages, not a compatibility guarantee. Headless UI listboxes are not detected, and I have not tried very long virtualized lists. If an option never appears in the DOM after opening or filtering the menu, the current lookup cannot pick it.

Project site and demo · Chrome Web Store listing

Top comments (0)