javascriptgoogle-chrome-extensionfirefox-addonrollbar

How to use Rollbar.js in Firefox Extension


I'm trying to implement rollbar.js to Firefox extentsion. However, there is no possibility to load it within "rollbar snippet" - it loads .js file from cdn - that's not allowed in Firefox addons.

So I reworked it and load rollbar.js from local file. This solution works in Chrome extension, however in Firefox addon I always get "Rollbar is undefined" ..

Here is the simplified code I use in poppup.html...

<script>
  chrome.storage.local.get(['optins'], function(value) {

    var rollbarOptIn = true;

    window._rollbarConfig = {
        accessToken: "xxx",
        captureUncaught: true,
        captureUnhandledRejections: true,
        enabled: rollbarOptIn,
        payload: {
            environment: "{{ ENVIRONMENT }}",
            client: {
              source_map_enabled: true,
              code_version: "{{ VERSION }}",
              guess_uncaught_frames: true
            }
        }
    };
  });
</script>
<script type="text/javascript" src="scripts/rollbar.js" async="false"></script>
<script>
  /* ugly workaround with set timeout... */
  setTimeout(function(){
    ...
    Rollbar.error("test");
    ...
  }, 600);
</script>

I am in the end.. please help.


Solution

  • Since chrome.storage is asynchronous its callback runs after rollbar.js so you probably have a browser-specific race condition between an asynchronous initialization in rollbar and that callback.

    Remove <script> from your HTML and try loading it dynamically, then use its onload event:

    chrome.storage.local.get('optins', ({optins}) => {
      window._rollbarConfig = {
        // ...............
      };
      const el = document.createElement('script');
      el.src = 'scripts/rollbar.js';
      el.onload = useRollbar;
      document.documentElement.appendChild(el);
    });
    
    function useRollbar() {
      Rollbar.error("test");
      // ...............
    }