如何在 Firefox 扩展中使用 Rollbar.js

How to use Rollbar.js in Firefox Extension

我正在尝试将 rollbar.js 实施到 Firefox 扩展。但是,无法在 "rollbar snippet" 内加载它 - 它从 cdn 加载 .js 文件 - 这在 Firefox 插件中是不允许的。

所以我修改了它并从本地文件加载rollbar.js。此解决方案适用于 Chrome 扩展,但是 在 Firefox 插件中我总是得到 "Rollbar is undefined" ..

这是我在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>

我在最后..请帮助。

由于 chrome.storage 是异步的,其回调在 rollbar.js 之后运行,因此您可能在 rollbar 中的异步初始化和该回调之间存在特定于浏览器的竞争条件。

从您的 HTML 中删除 <script> 并尝试动态加载它,然后使用它的 onload 事件:

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");
  // ...............
}