Home > Net >  Why is this Background.ts Chrome Extension script not installing with this Promise?
Why is this Background.ts Chrome Extension script not installing with this Promise?

Time:01-31

I am trying to initialize my localStorage using a Promise when I install/load/reload my Chrome Extension, but for some reason, this ModelDataColdSet call is preventing the Background script from running. I'm using Node 16.14.2.

ModelData.ts

export interface ModelData {
  cold?: Object
}

export type ModelDataKeys = keyof ModelData

export const ModelDataColdDefault = {}

export function ModelDataColdSet(cold: Object): Promise<void> {
  const values: ModelData = {
    cold,
  }
  return new Promise((resolve) => {
    chrome.storage.local.set(values, () => {
      resolve()
    })
  })
}

export function ModelDataColdGet(): Promise<Object> {
  const keys: ModelDataKeys[] = ["cold"]
  return new Promise((resolve) => {
    chrome.storage.local.get(keys, (res: ModelData) => {
      resolve(res.cold ?? {})
    })
  })
}

When I delete the ModelDataColdSet(ModelDataColdDefault) line and the Background script will run and print [Background] to the console. All of the tutorials I've found said this is the way to do it so I'm confused.

Background.ts

import { ModelDataColdDefault     , ModelDataColdSet }
  from './ModelData';
console.log('[Background]');

chrome.runtime.onInstalled.addListener(() => {
  console.log('Initializing extension');
  ModelDataColdSet(ModelDataColdDefault);
  
  chrome.alarms.create("FeedUpdate", {
    periodInMinutes: 1/60,
  });

  chrome.contextMenus.create({
    "id": "FeedAddSelectionContextMenu",
    "title": "Add selection to broadcast.",
    "contexts": ["selection"]
  });

  chrome.contextMenus.create({
    "id": "FeedAddPageContextMenu",
    "title": "Add current page to your mom."
  });
});

chrome.alarms.onAlarm.addListener((alarm) => {
  console.log('[onAlarm.FeedUpdate]');
  if (alarm.name === "FeedUpdate") {
    console.log('[onAlarm.FeedUpdate]');
  }
});

CodePudding user response:

The storage set is an async function so you need not to bother wrapping it in a promise.

export function ModelDataColdSet(cold: Object): Promise<void> {
    const values: ModelData = {
       cold,
    }
    return chrome.storage.local.set(values);
}
export function ModelDataColdGet(): Promise<object> {
    const keys: ModelDataKeys[] = ["cold"]
    return chrome.storage.local.get(keys)
}

CodePudding user response:

You don't need to wrap the storage set into a promise, it already is async. Try:

export function ModelDataColdSet(cold: Object): Promise<void> {
  const values: ModelData = {
    cold,
  }
  return chrome.storage.local.set(values);
}
export function ModelDataColdGet(): Promise<object> {
  const keys: ModelDataKeys[] = ["cold"]
  return chrome.storage.local.get(keys)
}

Also make sure that you have set the storage permission in your manifest.json

  • Related