🧩 Plasmo Developers�PD
🧩 Plasmo Developers3y ago
27 replies
jonah

Offscreen + Messaging API issue

Hello, I am trying to create an offscreen document for copying text to clipboard. I am trying to follow some of the examples I found in this issue: https://github.com/PlasmoHQ/plasmo/issues/527.

In my background.ts file, I am trying to send a message to my offscreen.ts file like this:
    const resp = await sendToBackground({
      name: "offscreen",
      body: {
        alias
      }
    })


this is the offscreen.ts file:
import OFFSCREEN_DOCUMENT_PATH from "url:~src/offscreen.html"

import type { PlasmoMessaging } from "@plasmohq/messaging"

const handler: PlasmoMessaging.MessageHandler = async (req, res) => {
  if (!(await chrome.offscreen.hasDocument())) {
    await chrome.offscreen.createDocument({
      url: OFFSCREEN_DOCUMENT_PATH,
      reasons: [chrome.offscreen.Reason.CLIPBOARD],
      justification: "Writing text to clipboard"
    })
  }

  const textEl: HTMLTextAreaElement = document.querySelector("#text")!
  textEl.value = req.body.alias
  textEl.select()
  document.execCommand("copy")

  res.send(true)
}

export default handler


Heres my offscreen.html:
<!DOCTYPE html>
<html>

<head>
    <title>Offscreen</title>
</head>

<body>
    <script src="offscreen.ts" type="module"></script>
</body>

</html>


But, when I try this, I get this error:
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist. Which I'm guessing means it can't find the message handler.

Am I supposed to put the message handler in a different place or create the offscreen document in a different file? I would really appreciate if someone could help me fix this.
Was this page helpful?