Skip to content
Advertisement

Chrome extension with SVG icons (chrome.browserAction.setIcon)

I am using scalable SVG icons in my Chrome extension.

JavaScript

I want to switch icons based on some parameters, so I have visual feedback.

What I have realized is that when I am switching icons very quickly, Chrome is messing up and often I end up seeing the wrong icon. I added console.log prints to code to ensure I am switching icons properly and I see that my code has no errors.

It looks like Chrome executes such change of icon requests asynchronously and conversion of SVG to pixels takes sometimes longer than usual. That leads to an execution in the wrong order.

So for example if I switch icons from A to B, then to C; then to D, … at the end I may see C, although the last request for change was to switch it to D.

Any ideas on how to fix this annoying problem?

Advertisement

Answer

  1. Chain the calls to the API using Promise
  2. If you call setIcon often, create a cache of imageData yourself and use it instead of path because the API re-reads the source icon each time and re-creates imageData.

Here’s a generic example, not tested:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement