benjypng / chrome-extension-logseq-quickcapture

chrome-extension-logseq-quickcapture

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Extension fails to capture a URL from managed profiles due to a race condition

sarahec opened this issue · comments

The Symptom

You click on the extension, logseq loads, but nothing is added. If you watch carefully, the URL includes undefined.

Additional testing shows that the page, append, title, and content fields of the URL are all undefined.

Root cause

The code is trying to use these values before their respective promises resolve (creating a race condition).

(incorrect code)

(async () => {
  const [tab] = await chrome.tabs.query({
    active: true,
    lastFocusedWindow: true,
  });

This does not automatically turn chrome.tabs.query synchronous. It returns a promise that still has to be resolved.

The fix

Package the top-level code into an async function then resolve the promise appropriately.

Example:

  async function getCurrentTab() {
    let [tab] = await chrome.tabs.query({
      active: true,
      lastFocusedWindow: true,
    });
    return tab;
  }

  getCurrentTab().then(tab => {
    // now it's defined
  });

The same problem affected reading the options with chrome.storage.sync.get -- they were undefined due to a race condition and also needed default values.

PR coming momentarily.

@hkgnp ping! Would you be willing to roll in this fix? There are reviews mentioning the two issues fixed here in the Chrome web store.