antfu / vitesse-webext

⚡️ WebExtension Vite Starter Template

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

LocalStorage is not kept in sync between the `Options`/`Popup` and `contentScripts`

PiiXiieeS opened this issue · comments

Description

LocalStorage is not kept in sync between the Options/Popup and contentScripts. Only initial value at initialisation is seen at all levels.

Reproduction

  • Clone repo and pnpm i
  • Run pnpm dev
  • Load the extension in the browser
  • Add this line to contentScripts/index.ts after console.info('[vitesse-webext] Hello world from content script')
    • console.info('[vitesse-webext] Storage loaded', JSON.stringify(storageDemo))
    • and importing the storage import { storageDemo } from '~/logic/storage'

From any website, while the web extension is loaded we will see in the browser console

[vitesse-webext] Storage loaded {"_shallow":false,"dep":{"w":0,"n":0},"__v_isRef":true,"_rawValue":"Storage Demo","_value":"Storage Demo"}

that is the storage initiated with value 'Storage Demo' used in `logic/storage.ts'

  • Then try to change this value in the Options page to 'New Storage Value'
  • This value will update the storage in the web extension and keep it reactive between the Options page and Popup. On the other hand the storage value seen from the contentScripts is all the time the initial value given at creation time = 'Storage Demo'

I would guess this local storage is different between the web extension and the page where the contentScripts are injected, but I am curious about why the initial value is properly seen in all the components including the contentScripts.

I can use messages to communicate between the Options/Popup pages and the contentScript but will be great to better understand this behaviour.

Environment

$ npx envinfo --system --binaries --browsers

System:

OS: macOS 11.1
CPU: (16) x64 Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz
Memory: 29.61 MB / 32.00 GB
Shell: 5.8 - /bin/zsh

Binaries:

Node: 16.0.0 - ~/.nvm/versions/node/v16.0.0/bin/node
npm: 7.23.0 - ~/.nvm/versions/node/v16.0.0/bin/npm

Browsers:

Chrome: 96.0.4664.110
Safari: 14.0.2

I thought the way to keep data synced is using background.js?
image
(from https://developer.chrome.com/docs/extensions/mv2/architecture-overview/#contentScripts)

@shaal, indeed. Why I was surprised in seeing the storage being initiated with the right data while it is just initiated in vue components.

commented

@PiiXiieeS storageDemo should not be accessed in content-scripts directly, because that Options/Popup is under chrome-extension://EXTENSION-ID domain but content-scripts are running at the website you opened.

You should use webext-bridge to get the latest storage value.