From d17e22a505e4dbfb96d2ea4cf7f8a745f5109dd9 Mon Sep 17 00:00:00 2001 From: Raymond Hill Date: Thu, 15 Jul 2021 13:14:37 -0400 Subject: [PATCH] Fix spurious error messages when updating contextual menu There were spurious error messages in the dev console of uBO in Firefox, because Firefox does not silently ignore duplicate contextual menu entries, which could occur transiently when the contextual menu entries were updated. The fix simplifies contextual menu code, and actually fulfill the original goal of avoiding to call extensions framework API as much as possible. --- platform/chromium/vapi-background.js | 33 ++++++++-------------------- platform/chromium/webext.js | 1 + 2 files changed, 10 insertions(+), 24 deletions(-) diff --git a/platform/chromium/vapi-background.js b/platform/chromium/vapi-background.js index f8e43dc94..c06aaf280 100644 --- a/platform/chromium/vapi-background.js +++ b/platform/chromium/vapi-background.js @@ -1415,35 +1415,20 @@ vAPI.Net = class { vAPI.contextMenu = webext.menus && { _callback: null, - _entries: [], - _createEntry: function(entry) { - webext.menus.create(JSON.parse(JSON.stringify(entry))); - }, + _hash: '', onMustUpdate: function() {}, setEntries: function(entries, callback) { entries = entries || []; - let n = Math.max(this._entries.length, entries.length); - for ( let i = 0; i < n; i++ ) { - const oldEntryId = this._entries[i]; - const newEntry = entries[i]; - if ( oldEntryId && newEntry ) { - if ( newEntry.id !== oldEntryId ) { - webext.menus.remove(oldEntryId); - this._createEntry(newEntry); - this._entries[i] = newEntry.id; - } - } else if ( oldEntryId && !newEntry ) { - webext.menus.remove(oldEntryId); - } else if ( !oldEntryId && newEntry ) { - this._createEntry(newEntry); - this._entries[i] = newEntry.id; - } + const hash = entries.map(v => v.id).join(); + if ( hash === this._hash ) { return; } + this._hash = hash; + webext.menus.removeAll(); + for ( const entry of entries ) { + webext.menus.create(JSON.parse(JSON.stringify(entry))); } - n = this._entries.length = entries.length; + const n = entries.length; callback = callback || null; - if ( callback === this._callback ) { - return; - } + if ( callback === this._callback ) { return; } if ( n !== 0 && callback !== null ) { webext.menus.onClicked.addListener(callback); this._callback = callback; diff --git a/platform/chromium/webext.js b/platform/chromium/webext.js index db7e7d4f9..1acb1ee56 100644 --- a/platform/chromium/webext.js +++ b/platform/chromium/webext.js @@ -73,6 +73,7 @@ const webext = { }, onClicked: chrome.contextMenus.onClicked, remove: promisifyNoFail(chrome.contextMenus, 'remove'), + removeAll: promisifyNoFail(chrome.contextMenus, 'removeAll'), }, // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/privacy privacy: {