PlasmoHQ / plasmo

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

[BUG] Can't use @plasmohq/storage in executeScript function #1083

Open chengfengfengwang opened 1 week ago

chengfengfengwang commented 1 week ago

What happened?

Can't use @plasmohq/storage in executeScript function, get '_storage is not defined' error

// background/index.ts

import Browser from "webextension-polyfill"
import { Storage } from "@plasmohq/storage"
Browser.action.onClicked.addListener((tab) => {
  if (!tab.url.includes("chrome://")) {
    Browser.scripting.executeScript({
      target: { tabId: tab.id, allFrames: true },
      func: ()=>{
        const storage = new Storage()
        console.log(storage); // _storage is not defined
      },
    })
  }
})

export {}

Version

Latest

What OS are you seeing the problem on?

MacOSX

What browsers are you seeing the problem on?

Chrome

Relevant log output

'_storage is not defined'

(OPTIONAL) Contribution

Code of Conduct

tbrockman commented 2 days ago

Not a Plasmo bug, see the related MDN documentation to learn more.

TL;DR is that you'll lose any external references passed to func. If your function is simple, you could just use the regular storage APIs.

If you don't need access to other Javascript running in the page and don't really want to use func, it'd probably be easier to create a content.ts file that just listens for a message from the background script (triggering whatever code you want to run), and then have the background script send a message when the browser action is clicked.