Fix API calls from content scripts in Firefox

This fixes the avatars and autorefresh features in Firefox, which didn't
work until now due to the fact that API calls from content scripts
included a |null| value in the |origin| header and this caused the
requests to fail.

Fixed: twpowertools:68
Change-Id: Ia4f5817774d7e38f375a97c3a8c29d524ea4ea90
diff --git a/src/common/api.js b/src/common/api.js
index 16385a9..11c0ad6 100644
--- a/src/common/api.js
+++ b/src/common/api.js
@@ -28,15 +28,25 @@
   let authuserPart =
       authuser == '0' ? '' : '?authuser=' + encodeURIComponent(authuser);
 
-  return fetch(CC_API_BASE_URL + method + authuserPart, {
-           'headers': {
-             'content-type': 'text/plain; charset=utf-8',
-           },
-           'body': JSON.stringify(data),
-           'method': 'POST',
-           'mode': 'cors',
-           'credentials': (authenticated ? 'include' : 'omit'),
-         })
+  // #!if browser_target == 'gecko'
+  // See
+  // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#xhr_and_fetch
+  // and https://developer.mozilla.org/en-US/docs/Web/API/Window/content.
+  const context = window.content || window;
+  // #!else
+  const context = window;
+  // #!endif
+
+  return context
+      .fetch(CC_API_BASE_URL + method + authuserPart, {
+        'headers': {
+          'content-type': 'text/plain; charset=utf-8',
+        },
+        'body': JSON.stringify(data),
+        'method': 'POST',
+        'mode': 'cors',
+        'credentials': (authenticated ? 'include' : 'omit'),
+      })
       .then(res => {
         if (res.status == 200 || res.status == 400) {
           return res.json().then(data => ({
diff --git a/src/contentScripts/communityConsole/avatars.js b/src/contentScripts/communityConsole/avatars.js
index 41ccd1c..9c555b9 100644
--- a/src/contentScripts/communityConsole/avatars.js
+++ b/src/contentScripts/communityConsole/avatars.js
@@ -156,6 +156,9 @@
             // cache.
             lastMessageId: data?.['1']?.['2']?.['10'],
           };
+        })
+        .catch(cause => {
+          throw new Error('Failed ViewThread request.', {cause});
         });
   }