Chrome 扩展:正确添加具有非持久背景页面的上下文菜单条目

2023-11-29

我正在开发一个简单的链接共享扩展(插板、可读性、美味等),并且有一个关于如何正确处理上下文菜单项的问题。在我的非持久后台页面中,我调用chrome.contextMenus.create and chrome.contextMenus.onClicked.addListener设置/响应上下文菜单。

上下文菜单条目按预期工作。但背景页面显示以下错误(在它启动之后和我使用该条目之前):

contextMenus.create: Cannot create item with duplicate id id_share_link at chrome-extension://.../share.js:52:30 lastError:29 set  

这让我意识到我在任何时候都不会删除该项目或侦听器。对 javascript 和扩展知之甚少,我想知道我是否做对了一切。我假设每次调用后台页面时都会重新执行此顶级代码。因此,将会有多余的 create 和 addListener 调用(因此我看到的错误被记录)。

我显然无法响应挂起而进行清理,因为需要存在这些调用来唤醒后台脚本。

我应该以不同的方式处理事情吗?


如果您想使用活动页面, ie a 非持久背景页面,正如你所说,你应该通过注册一个上下文菜单contextMenus.create在事件处理程序中runtime.onInstalled,因为这些上下文菜单注册无论如何都会“持续”。

You have to add the listener-function for the contextMenus.onClicked event every time the event page gets reloaded, though, as the registration of your wish to listen on that event persists, while the handler callback itself does not. So generally don't call contextMenus.onClicked.addListener from runtime.onInstalled, but from top level or other code, that is guaranteed to be executed each time the event page loads.[1]

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Chrome 扩展:正确添加具有非持久背景页面的上下文菜单条目 的相关文章

随机推荐