background.js 1.7 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import whenAllSettled from 'when-all-settled';
  2. import { makeRemotelyCallable, remoteFunction } from 'webextension-rpc';
  3. function normaliseUrl(url) {
  4. // Remove the fragment identifier, if any.
  5. url = url.split('#')[0]
  6. // Ignore the URL scheme for authority based URLs (see e.g. RFC 2396 section 3). In other words,
  7. // we disregard whether a document was loaded through https or http or whatever other protocol.
  8. url = url.replace(/^[^:]+:\/\//, '//')
  9. return url
  10. }
  11. async function retrieveBookmarks({ url }) {
  12. const bookmarkTree = await browser.bookmarks.getTree();
  13. const toScan = [...bookmarkTree];
  14. const allBookmarks = [];
  15. while (toScan.length > 0) {
  16. const next = toScan.shift();
  17. if (next.url) {
  18. allBookmarks.push(next);
  19. }
  20. if (next.children) {
  21. toScan.push(...next.children);
  22. }
  23. }
  24. const matchingBookmarks = allBookmarks.filter(
  25. bookmark => normaliseUrl(bookmark.url) === normaliseUrl(url)
  26. );
  27. return matchingBookmarks;
  28. }
  29. makeRemotelyCallable({
  30. retrieveBookmarks,
  31. });
  32. async function onBookmarkChange() {
  33. // Update the bookmarks in every tab. We simply message every tab, as we do not know which ones
  34. // contain our audio players.
  35. const tabs = await browser.tabs.query({ status: 'complete' });
  36. const refreshingPromises = tabs.map(tab =>
  37. remoteFunction('displayBookmarksInPage', { tabId: tab.id })()
  38. );
  39. // Wait until all tabs completed, ignoring any errors.
  40. await whenAllSettled(refreshingPromises);
  41. }
  42. browser.bookmarks.onCreated.addListener(onBookmarkChange);
  43. browser.bookmarks.onRemoved.addListener(onBookmarkChange);
  44. browser.bookmarks.onChanged.addListener(onBookmarkChange);
  45. if (browser.bookmarks.onImportEnded) {
  46. browser.bookmarks.onImportEnded.addListener(onBookmarkChange);
  47. }