russhwolf / multiplatform-settings

A Kotlin Multiplatform library for saving simple key-value data
Apache License 2.0
1.7k stars 67 forks source link

ERROR ReferenceError: localStorage is not defined on Web Extension #165

Closed ar-g closed 1 year ago

ar-g commented 1 year ago

I'm currently getting:

ERROR ReferenceError: localStorage is not defined
    at new StorageSettings (MultiplatformSettings-multiplatform-settings.js:61:1)
    at new LocalStorageSettings (common-store.js:273:1)

When trying to initialise Settings in web-extension:

StorageSettings()

Is there a specific place I should be trying to do it?

ar-g commented 1 year ago

After more investigation it looks like there's needs to be implemented fallback in order to run on the WebExtension. More info here: https://stackoverflow.com/questions/40887635/access-localstorage-from-service-worker and here https://stackoverflow.com/questions/70704283/how-to-use-localstorage-or-an-alternative-in-manifest-v3

So far I've tried this with no luck

StorageSettings(
                delegate = js("self.chrome.storage.local") as? Storage ?: js("self.localStorage") as? Storage ?: error("Could not create chrome.storage.local"),
            )
ar-g commented 1 year ago

made some progress with this interface:

public external interface ChromeStorage {
    fun set(items: dynamic): Promise<Unit>
    fun get(key: String): Promise<dynamic>
    fun remove(key: String): Promise<Unit>
    fun clear(): Promise<Unit>
}

which is doesn't really fit synchronous interface of Settings, so I'd probably have to throw away the library and roll different implementations with suspend as part of the interface

russhwolf commented 1 year ago

You might be able to get it working with the SuspendSettings interface in the coroutines module.

russhwolf commented 1 year ago

@ar-g Do you still need help here? I'm inclined to close this unless you think there's something the library could add that would help your use-case.

aggarwalpulkit596 commented 11 months ago

Hey wanted to confirm if we tend to use the SuspendSettings, the library would work even with web worker ?

russhwolf commented 10 months ago

@aggarwalpulkit596 The library is not doing anything explicitly to help you with web worker. But if you have a Promise-based interface like the ChromeStorage defined above, you should be able to convert the promises to suspend functions and use that to write a custom implementation of SuspendSettings.