简体   繁体   中英

Asynchronous operation in blocking chrome.webRequest.onBeforeSendHeaders listener

I'm developing a Chrome extension, and have run into an issue due to developing against a mixture of synchronous and asynchronous apis.

chrome.webRequest.onBeforeSendHeaders.addListener(function(details) {
  //code that modifies details.requestHeaders
  //..
  return {requestHeaders: details.requestHeaders};
},
{urls: ["<all_urls>"]},
["blocking", "requestHeaders"]

Inside the listener function I want to fetch data from IndexedDB and modify the request headers based on this data. IndexedDB only has an asynchronous API, while the contract for the listener requires it to be synchronous.

Any ideas how I could solve this problem?

A DB call is generally too expensive. That said, here is one idea off the top of my head (which might be horrible):

  • Keep an in memory cache of most frequently used data. Use some type of simple data structure like a Map .
  • Pre-populate the map when the app loads with whatever data is most likely to be needed. Do this when the extension background page loads.
  • Periodically update the cache's contents during the runtime lifecycle when appropriate. Do this from the app's background page, using an alarm to trigger an update on a schedule. Register the alarm on background page load/app startup.
  • Query the in memory map in onBeforeSendHeaders. Map lookups are synchronous and fast. If the lookup works, great. If it fails, think of an error handling mechanism (if you call this an error).
  • When a cache miss occurs, trigger an async call (for which you don't need to wait to resolve) that eventually logs the cache miss to another data structure. The same other structure you use for the code that periodically updates the map.
  • When a cache hit occurs, trigger an async call that increases the chance the value remains in the map, and slightly decrease the chance for other items in the cache (perhaps that is implicit in the increase).
  • Don't forget to prune the cache in the background cache update for items that are no longer likely
  • Experiment with a cache size that yields decent performance and reasonably memory usage.

That being said, you would need to think of the user experience in the event of a cache miss. Maybe supply a default parameter, or a placeholder value of some sort that notifies the user of the miss somehow. It kind of depends on how you want the app to work and what the app does, which you did not state.

Oh, derp, and consider using localStorage as the in memory map... Duh.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM