Published on

Browser Autofills are their own standards

Authors
  • avatar
    Name
    Sedky Haider
    Twitter

If you're using Google Maps Autocomplete, chances are your application expects users to interact with Autocomplete suggestions in order to "move forward" with the next phase of your app. This is especially true in single page Javascript applications (SPA).

However - Browser autofills will NOT trigger fires of Google Maps Autocomplete listeners.

Here's what your autocomplete listener might look like:

const autocomplete = new window.google.maps.places.Autocomplete(addressInputRef.current, {
    componentRestrictions: { country: "ca" },
    fields: ["formatted_address", "address_components", "geometry"],
    types: ["address"],
});

// Add listener on the autocomplete
const listener = autocomplete.addListener("place_changed", async () => {
    const place = autocomplete.getPlace();
    if (place.address_components) {
        // some logic
    }
});

The above autocomplete listeners you place on the Address input will NOT be fired by the Browser's autofill.

The autocomplete attribute tells the browser how to handle autofilling for a particular form field. Frustratingly, Google's own Chrome Autofill doesn't respect autocomplete="off".

This behaviour results in Google Chrome getting in the way of Google Maps - lol. Here's an explanation of why browsers do this now. As always, the answer is always security!

Note: though the linked post contains a great answer, many of the workarounds on that page are no longer valid.

Here is a workaround that prevents the user's browser from autofilling addresses and thus bypassing the Google listener:

// Wrapper for "<input />"
<OutlinedInput
  defaultValue=""
  id="address"
  inputRef={addressInputRef}
  name="address1"
  type="text"
  placeholder="Enter a location"
  // Hack to prevent the Browser auto fill from working
  onFocus={(e) => e.target.setAttribute('autocomplete', 'new-password')}
  autoComplete="new-password"
/>

Setting autocomplete="new-password" explicitly instructs the browser not to autofill the field with previously saved data. The "new-password" value is a special case intended for password fields where the user is expected to create a new password (not use an old one). Browsers treat this attribute as a signal not to autofill.

Setting this attribute dynamically on onFocus (when the user clicks or tabs into the field) is important because some browsers may ignore the autocomplete attribute if it's present when the page initially loads. By changing the attribute only when the field is focused, you "trick" the browser into changing its behavior and not offering its autofill options at that moment.