How can I use Floating UI as a Chrome extension content script?

167 Views Asked by At

The goal is to insert tooltips into specific elements on web pages using the Chrome extension.

I tried using the ESM version of Floating UI as a content script but getting this error:

Uncaught SyntaxError: Cannot use import statement outside a module

import{computePosition as t,rectToClientRect as e}from"/npm/@floating-ui/[email protected]/+esm";

The manifest looks smth like that:

  "content_scripts": [
    {
      "matches": [
        "*://*/*"
      ],
      "js": [
        "floating-esm.js",
        "content.js"
      ],
      "type": "module",
      "css": [
        "tooltips.css"
      ]
    }
  ],

Was expecting to have access to computePosition function in the main content script file.

1

There are 1 best solutions below

1
atjackiejohns On

Essentially imported Core and Dom and changed the update() function a bit like to include window.FloatingUIDOM and window.FloatingUICore:

    window.FloatingUIDOM.computePosition(markedDiv, tooltip, {
  placement: "top",
  middleware: [
    window.FloatingUICore.offset(6),
    window.FloatingUIDOM.flip(),
    window.FloatingUIDOM.shift({ padding: 5 }),
    window.FloatingUIDOM.arrow({ element: arrowElement }),
  ],
})

I think in their original sample code the markedDiv was called "button" but it doesn't matter much.