webextension-polyfill-ts#browser TypeScript Examples

The following examples show how to use webextension-polyfill-ts#browser. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From clarity with Apache License 2.0 7 votes vote down vote up
export function updateBadge(appState: AppState) {
  let label = '';
  let count = appState.toSignMessages.length;
  if (appState.connectionRequested) {
    label = '1';
  } else if (count) {
    label = String(count);
  }
  browser.browserAction.setBadgeText({ text: label });
  browser.browserAction.setBadgeBackgroundColor({ color: 'red' });
}
Example #2
Source File: utils.ts    From signer with Apache License 2.0 7 votes vote down vote up
export function updateBadge(appState: AppState) {
  let label = '';
  let count =
    appState.unsignedDeploys.length > 0
      ? appState.unsignedDeploys.length
      : appState.unsignedMessages.length > 0
      ? appState.unsignedMessages.length
      : undefined;
  if (appState.connectionRequested && !appState.connectionStatus) {
    label = '1';
  } else if (count) {
    label = String(count);
  }
  browser.browserAction.setBadgeText({ text: label });
  browser.browserAction.setBadgeBackgroundColor({ color: 'red' });
}
Example #3
Source File: ConnectionManager.ts    From clarity with Apache License 2.0 6 votes vote down vote up
public requestConnection() {
    if (!this.isConnected()) {
      this.appState.connectionRequested = true;
      browser.notifications.create({
        title: 'Connection Request',
        iconUrl: browser.extension.getURL('logo64.png'),
        message: 'Open Signer to Approve or Reject Connection',
        type: 'basic'
      });
    }
  }
Example #4
Source File: background.ts    From twitch-live-extension with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
browser.runtime.onMessage.addListener(async (msg: BackgroundMessage) => {
    if (msg.type === MESSAGE_TYPES.GET_TOKEN) {
        const token = await fetchToken(!!msg.data.prompt);
        // Since on Firefox the onMessage listener doesn't return the response
        // I need to call storeToken here instead of in the method that requests the token
        localStorageService.storeToken(token);
    } else if (msg.type === MESSAGE_TYPES.ENABLE_NOTIFICATIONS) {
        browser.alarms.create(POOLING_ALARM_NAME, { periodInMinutes: POOLING_JUST_WENT_LIVE });
    } else if (msg.type === MESSAGE_TYPES.DISABLE_NOTIFICATIONS) {
        await browser.alarms.clear(POOLING_ALARM_NAME);
    } else if (msg.type === MESSAGE_TYPES.UPDATE_BADGE_ICON) {
        await displayNumberOfLivestreams(msg.data.nrStreams);
    }
});
Example #5
Source File: index.ts    From bitpay-browser-extension with MIT License 6 votes vote down vote up
async function launchWindowAndListenForEvents({
  url,
  height = 735,
  width = 430
}: {
  url: string;
  height: number;
  width: number;
}): Promise<GiftCardInvoiceMessage> {
  const { id, height: winHeight, width: winWidth } = await browser.windows.create({
    url,
    type: 'popup',
    height,
    width
  });
  if ((winHeight as number) !== height || (winWidth as number) !== width) {
    await browser.windows.update(id as number, { height, width });
  }
  const promise = new Promise<GiftCardInvoiceMessage>(resolve => {
    windowIdResolveMap[id as number] = resolve as () => GiftCardInvoiceMessage;
  });
  const message = await promise;
  return message;
}
Example #6
Source File: PopupManager.ts    From signer with Apache License 2.0 6 votes vote down vote up
async closePopup(windowId?: number, signingId?: number) {
    try {
      if (signingId) this.cancelUnsignedItem(signingId);
      if (windowId) {
        await browser.windows.remove(windowId);
      } else {
        // This allows the FE to call close popup without querying for window id to pass.
        let currentWindow = await browser.windows.getCurrent();
        if (currentWindow.type === 'popup' && currentWindow.id) {
          await browser.windows.remove(currentWindow.id);
        }
      }
      // Reset popup state
      popupWindow = null;
    } catch (error) {
      throw error;
    }
  }
Example #7
Source File: index.ts    From apps with GNU Affero General Public License v3.0 6 votes vote down vote up
sendBootData = async (req, sender) => {
  if (isExcluded(sender?.origin)) {
    return;
  }

  const cacheData = getLocalBootData();
  if (cacheData.settings?.optOutCompanion) {
    return;
  }

  const url = sender?.tab?.url;

  const [deviceId, { postData, settings, flags, user, alerts, visit }] =
    await Promise.all([getOrGenerateDeviceId(), getBootData('companion', url)]);

  let settingsOutput = settings;
  if (!cacheData?.user || !('providers' in cacheData?.user)) {
    settingsOutput = { ...settingsOutput, ...cacheData?.settings };
  }
  await browser.tabs.sendMessage(sender?.tab?.id, {
    deviceId,
    url,
    postData,
    settings: settingsOutput,
    flags,
    user,
    alerts,
    visit,
  });
}
Example #8
Source File: background.ts    From devtools-ds with MIT License 6 votes vote down vote up
browser.runtime.onConnect.addListener(function (port) {
  if (port.name === PORT_NAME) {
    // Connection from DevTools Panel
    const panelListener = function (message: Message) {
      if (message.type === "connect" && message.tabId) {
        controller.connect(message.tabId, port);
      }

      // Pass message to content script
      controller.toContent(message.tabId, message);
    };

    // Attach listener to the Panel
    port.onMessage.addListener(panelListener);

    // Handle Panel disconnect
    port.onDisconnect.addListener(function (p) {
      const message: DisconnectMessage = {
        type: "disconnect",
        source: PANEL_SOURCE,
        tabId: 0,
      };
      controller.disconnect(p, message);
    });
  }
});
Example #9
Source File: index.ts    From bob-extension with MIT License 6 votes vote down vote up
async function openPopup() {

  const tab = await browser.tabs.create({
    url: browser.extension.getURL('popup.html'),
    active: false,
  });

  const popup = await browser.windows.create({
    tabId: tab.id,
    type: 'popup',
    focused: true,
    width: 357,
    height: 600,
  });

  return popup;
}
Example #10
Source File: browser.ts    From roam-toolkit with MIT License 6 votes vote down vote up
Browser = {
    goToPage: (url: string) => (window.location.href = url),

    getActiveTabUrl: () => new URL(window.location.href),

    // Does not work from content script
    getActiveTab: () => browser.tabs.query({currentWindow: true, active: true}).then(tabs => tabs[0]),

    sendMessageToActiveTab(message: any) {
        return this.getActiveTab().then(tab => browser.tabs.sendMessage(tab.id!, message))
    },

    addMessageListener(callback: (message: any) => Promise<void> | undefined) {
        browser.runtime.onMessage.addListener(callback)
    },
}
Example #11
Source File: index.ts    From overleaf-textarea with GNU General Public License v3.0 6 votes vote down vote up
// checks the first time whether the plugin is active
browser.storage.sync.get(['active']).then(result => {
  active = result.active === undefined ? true : result.active;
  if (active) {
    createPluginElement();
    getSpellCheckTextElement()?.addEventListener('input', () => {
      controller.textAreaInputChangeEvent()
    });
    setTextareaScrollListener();

    //Timeout because grammarly has not loaded yet.
    setTimeout(() => {
      const textarea = getSpellCheckTextElement();
      if(textarea){
        const current = document.activeElement;
        getSpellCheckTextElement()!.selectionEnd = 1;
        getSpellCheckTextElement()?.focus();

        (current as HTMLElement)?.focus();
      }
    }, 2000)
  }
});
Example #12
Source File: Fullscreen.tsx    From pali-wallet with MIT License 6 votes vote down vote up
Fullscreen: React.FC = () => {
  const url = browser.runtime.getURL('app.html');
  if (!url) return <></>;

  return (
    <div
      className="fixed bottom-0 left-0 flex gap-2 items-center justify-center p-4 w-full text-brand-white text-sm bg-bkg-4 cursor-pointer sm:hidden"
      onClick={() => window.open(url)}
    >
      <Icon name="desktop" className="mb-1 text-brand-white" />

      <p>Fullscreen mode</p>
    </div>
  );
}
Example #13
Source File: onTextlintWorker.ts    From editor with MIT License 6 votes vote down vote up
listenOnTextlintWorkerJsUrl = (args: listenOnTextlintWorkerJsUrlArgs) => {
    browser.tabs.onUpdated.addListener((tabId, changeInfo, _tab) => {
        if (changeInfo && changeInfo.url && isTextlintWorkerUrl(changeInfo.url)) {
            args.onTextlintWorkerUrl({
                tabId,
                url: changeInfo.url
            });
        }
    });
    browser.tabs.onActivated.addListener(async (activeInfo) => {
        const tab = await browser.tabs.get(activeInfo.tabId);
        if (tab && tab.id && tab.url && isTextlintWorkerUrl(tab.url)) {
            args.onTextlintWorkerUrl({
                tabId: tab.id,
                url: tab.url
            });
        }
    });
}
Example #14
Source File: background.ts    From clarity with Apache License 2.0 5 votes vote down vote up
// Setup RPC server for Popup
async function setupPopupAPIServer() {
  const rpc = new Rpc({
    addListener: browser.runtime.onMessage.addListener,
    destination: 'popup',
    postMessage: browser.runtime.sendMessage,
    source: 'background'
  });
  // once appState update, send updated appState to popup
  autorun(() => {
    rpc.call<void>('popup.updateState', appState).catch(e => {
      console.log(e);
    });
    updateBadge(appState);
  });
  rpc.register(
    'account.unlock',
    accountController.unlock.bind(accountController)
  );
  rpc.register(
    'account.createNewVault',
    accountController.createNewVault.bind(accountController)
  );
  rpc.register('account.lock', accountController.lock.bind(accountController));
  rpc.register(
    'account.importUserAccount',
    accountController.importUserAccount.bind(accountController)
  );
  rpc.register(
    'account.removeUserAccount',
    accountController.removeUserAccount.bind(accountController)
  );
  rpc.register(
    'account.renameUserAccount',
    accountController.renameUserAccount.bind(accountController)
  );
  rpc.register(
    'account.reorderAccount',
    accountController.reorderAccount.bind(accountController)
  );
  rpc.register(
    'account.getSelectUserAccount',
    accountController.getSelectUserAccount.bind(accountController)
  );
  rpc.register(
    'account.resetVault',
    accountController.resetVault.bind(accountController)
  );
  rpc.register(
    'account.switchToAccount',
    accountController.switchToAccount.bind(accountController)
  );
  rpc.register('background.getState', () => {
    return appState;
  });
  rpc.register(
    'sign.signMessage',
    signMessageManager.approveMsg.bind(signMessageManager)
  );
  rpc.register(
    'sign.rejectMessage',
    signMessageManager.rejectMsg.bind(signMessageManager)
  );
  rpc.register(
    'connection.requestConnection',
    connectionManager.requestConnection.bind(connectionManager)
  );
  rpc.register(
    'connection.resetConnectionRequest',
    connectionManager.resetConnectionRequest.bind(connectionManager)
  );
  rpc.register(
    'connection.connectToSite',
    connectionManager.connectToSite.bind(connectionManager)
  );
  rpc.register(
    'connection.disconnectFromSite',
    connectionManager.disconnectFromSite.bind(connectionManager)
  );
}
Example #15
Source File: background.ts    From twitch-live-extension with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
browser.alarms.create(BADGE_ICON_ALARM_NAME, { periodInMinutes: 1 });
Example #16
Source File: index.ts    From bitpay-browser-extension with MIT License 5 votes vote down vote up
function setIcon(bitpayAccepted: boolean): void {
  browser.browserAction.setIcon({ path: getIconPath(bitpayAccepted) });
}
Example #17
Source File: PopupManager.ts    From signer with Apache License 2.0 5 votes vote down vote up
async openPopup(purposeForOpening: PurposeForOpening, signingId?: number) {
    if (!popupWindow) {
      // No popup window open
      browser.windows
        .getCurrent()
        .then(window => {
          let windowWidth = window.width ?? popupDimensions.defaultWidth;
          let xOffset = window.left ?? 0;
          let yOffset = window.top ?? 0;
          let popupWidth =
            purposeForOpening === PurposeForOpening.SignDeploy
              ? popupDimensions.expandedWidth
              : popupDimensions.defaultWidth;
          browser.windows
            .create({
              url:
                purposeForOpening === PurposeForOpening.ImportAccount
                  ? 'index.html?#/import'
                  : 'index.html?#/',
              type: 'popup',
              height:
                purposeForOpening === PurposeForOpening.SignDeploy
                  ? popupDimensions.expandedHeight
                  : popupDimensions.defaultHeight,
              width: popupWidth,
              left: windowWidth + xOffset - popupWidth - popupBuffer.right,
              top: yOffset + popupBuffer.top
            })
            .then(newPopup => {
              if (newPopup.id) {
                popupWindow = {
                  windowId: newPopup.id,
                  purposeForOpening,
                  signingId
                };
              }
            });
        })
        .catch(() => {
          let title, message;
          switch (purposeForOpening) {
            case PurposeForOpening.Connect:
              title = 'Connection Request';
              message = 'Open Signer to Approve or Reject Connection';
              break;
            case PurposeForOpening.SignDeploy:
            case PurposeForOpening.SignMessage:
              title = 'Signature Request';
              message = 'Open Signer to Approve or Cancel Signing';
              break;
            default:
              throw new Error('Purpose for alert message not found!');
          }
          browser.notifications.create({
            title: title,
            iconUrl: browser.extension.getURL('logo64.png'),
            message: message,
            type: 'basic'
          });
        });
    } else {
      // There is a popup window open already
      if (popupWindow.purposeForOpening === purposeForOpening) {
        // popup window is open to the required page
        let window = await browser.windows.get(popupWindow.windowId);
        if (window.id) {
          browser.windows.update(window.id, {
            // Bring popup window to the front
            focused: true,
            drawAttention: true
          });
        }
      } else {
        // popup window is open to another page
        await this.closePopup(popupWindow.windowId);
        await this.openPopup(purposeForOpening);
      }
    }
  }
Example #18
Source File: index.ts    From apps with GNU Affero General Public License v3.0 5 votes vote down vote up
async function handleMessages(message, sender) {
  await getContentScriptPermissionAndRegister();

  if (message.type === 'CONTENT_LOADED') {
    sendBootData(message, sender);
    return null;
  }

  if (message.type === 'GRAPHQL_REQUEST') {
    const { requestKey } = message.headers || {};
    const req = request(message.url, message.document, message.variables);

    if (!requestKey) {
      return req;
    }

    const key = parseOrDefault(requestKey);
    const url = sender?.tab?.url?.split('?')[0];
    const [deviceId, res] = await Promise.all([getOrGenerateDeviceId(), req]);

    return browser.tabs.sendMessage(sender?.tab?.id, {
      deviceId,
      url,
      res,
      req: { variables: message.variables },
      key,
    });
  }

  if (message.type === 'FETCH_REQUEST') {
    return fetch(message.url, { ...message.args });
  }

  if (message.type === 'DISABLE_COMPANION') {
    const cacheData = getLocalBootData();
    const settings = { ...cacheData.settings, optOutCompanion: true };
    localStorage.setItem(
      BOOT_LOCAL_KEY,
      JSON.stringify({ ...cacheData, settings, lastModifier: 'companion' }),
    );
    return request(`${apiUrl}/graphql`, UPDATE_USER_SETTINGS_MUTATION, {
      data: {
        optOutCompanion: true,
      },
    });
  }
  return null;
}