PlasmoHQ / plasmo

🧩 The Browser Extension Framework
https://www.plasmo.com
MIT License
10.14k stars 350 forks source link

[BUG] useMessage in main world content script is undefined #834

Closed the-wc closed 9 months ago

the-wc commented 9 months ago

What happened?

useMessage OR chrome.runtime.onMessage.addListener results in: onMessage.addListener is undefined. Hoping that I'm just misconfigured, but here's the code:

// contents/content.tsx
export const config: PlasmoCSConfig = {
  matches: ["<all_urls>"],
  all_frames: true,
  run_at: "document_start",
  world: "MAIN"
}

export const getStyle = () => {
  const style = document.createElement("style")
  style.textContent = cssText
  return style
}

const PlasmoOverlay = () => {
  const { data } = useMessage<string, string>(async (req, res) => {
    console.log("useMessage()")
  })

  return <ContentHost />
}

export default PlasmoOverlay

Manifest Configuration:

"manifest": {
    "host_permissions": [
      "https://*/*",
      "http://*/*"
    ],
    "permissions": [
      "activeTab",
      "tabs",
      "cookies",
      "contextMenus",
      "scripting"
    ],
    "externally_connectable": {
      "matches": [
        "https://*/*",
        "http://*/*"
      ]
    }
  }

Version

Latest

What OS are you seeing the problem on?

Linux

What browsers are you seeing the problem on?

Chrome

Relevant log output

hook.cjs:1 Uncaught TypeError: Cannot read properties of undefined (reading 'addListener')

(OPTIONAL) Contribution

Code of Conduct

the-wc commented 9 months ago

This is a rookie mistake. You cannot access the chrome.runtime in main world.

However main world scripts are injected prevents you from accessing the chrome.runtime properties like onMessage or addListener. So, you will not be able to access useMessage or have a receipient for sendToContentScript, which rely on the runtime.

Simple example:

export const config: PlasmoCSConfig = {
  // Do not include the below in your content script, if you need to access the `chrome.runtime` properties
  // world: "MAIN"
}