如何在webextension-polyfill中设置代理对象 [火狐]

huangapple go评论64阅读模式
英文:

How to set an proxy object in webextension-polyfill [firefox]

问题

我目前正在开发一个扩展程序。该扩展程序首先在Chrome中完成,一切正常,但当我尝试在Firefox中使用相同的扩展程序时,我收到了错误:DataCloneError:无法克隆代理对象

我正在使用VueJSPinia,这两个库都使用Proxies来处理它们的响应性。

目前导致我的应用程序出现问题的特殊代码片段是:

import browser from 'webextension-polyfill';

interface ProjectCodec { id: string; }

export const setProjectForRecording = async (project: ProjectCodec) => {
  await browser.storage.local.set({
    [CURRENT_PROJECT_FOR_RECORDING_KEY]: project
  })
}

当我执行console.log(project)时,我得到:

Proxy { <target>: {...}, <handler>: {...} }

从看起来的情况来看,当我们使用browser.storage.local.set时,我们无法将Proxy对象传递给它。然后我尝试了:

await browser.storage.local.set({
    [CURRENT_PROJECT_FOR_RECORDING_KEY]: Object.assign({}, project)
  })

但仍然发生相同的错误。这是否是库的错误,还是我做错了什么?我尝试了几种其他Object.assign()的变化,但没有成功。

英文:

I'm currently working on an extension. The extension was done firstly in Chrome and everything works there, but when I try to use the same extension in Firefox I get Error: DataCloneError: Proxy object could not be cloned.

I'm using VueJS and Pinia and both of these libraries uses Proxies to handle their reactivity.

The special piece of code that is currently breaking my app is:

import browser from &#39;webextension-polyfill&#39;

interface ProjectCodec { id: string; }

export const setProjectForRecording = async (project: ProjectCodec) =&gt; {
  await browser.storage.local.set({
    [CURRENT_PROJECT_FOR_RECORDING_KEY]: project
  })
}

When I do a console.log(project) I get:

Proxy { &lt;target&gt;: {…}, &lt;handler&gt;: {…} }

From what it looks like when we use browser.storage.local.set we can't pass a Proxy object to it. Then I tried:

await browser.storage.local.set({
    [CURRENT_PROJECT_FOR_RECORDING_KEY]: Object.assign({}, project)
  })

But the same error happens. Is this a bug with the library or am I doing something wrong? I tried a couple other variations of Object.assign() but no luck there.

答案1

得分: 1

这是Firefox中的一个非常令人讨厌的错误,他们声称这是有意的行为,所以你必须自己创建一个克隆,例如JSON.parse(JSON.stringify(project))或一个深拷贝函数(有多个示例可用)。

英文:

It's a super annoying bug in Firefox that they claim as intentional behavior, so you'll have to make a clone yourself e.g. JSON.parse(JSON.stringify(project)) or a deepCopy function (there are multiple examples around).

huangapple
  • 本文由 发表于 2023年6月15日 23:37:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76483317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定