How to use webextension-polyfill - 10 common examples

To help you get started, we’ve selected a few webextension-polyfill examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github glacambre / firenvim / src / NeovimFrame.ts View on Github external
const [major, minor, patch] = extInfo.version.split(".");
        nvim.set_client_info(extInfo.name,
            { major, minor, patch },
            "ui",
            {},
            {},
        );

        await confReady;
        nvim.ui_attach(cols, rows, {
            ext_linegrid: true,
            ext_messages: getConfForUrl(url).cmdline === "firenvim",
            rgb: true,
        });
        let resizeReqId = 0;
        browser.runtime.onMessage.addListener((request: any, sender: any, sendResponse: any) => {
            if (request.selector === selector
                && request.funcName[0] === "resize"
                && request.args[0] > resizeReqId) {
                const [id, width, height] = request.args;
                resizeReqId = id;
                // We need to put the keyHandler at the origin in order to avoid
                // issues when it slips out of the viewport
                keyHandler.style.left = `0px`;
                keyHandler.style.top = `0px`;
                // It's tempting to try to optimize this by only calling
                // ui_try_resize when nCols is different from cols and nRows is
                // different from rows but we can't because redraw notifications
                // might happen without us actually calling ui_try_resize and then
                // the sizes wouldn't be in sync anymore
                const [cellWidth, cellHeight] = getCharSize(host);
                const nCols = Math.floor(width / cellWidth);
github lusakasa / saka / src / background_page / index.js View on Github external
async function toggleSaka(tabId) {
  if (SAKA_DEBUG) console.group('toggleSaka');
  // Get the specified tab, or the current tab if none is specified
  const currentTab =
    tabId === undefined
      ? (await browser.tabs.query({
          active: true,
          currentWindow: true
        }))[0]
      : await browser.tabs.get(tabId);
  if (currentTab) {
    // If the current tab is Saka, switch to the previous tab (if it exists) and close the current tab
    if (currentTab.url === browser.runtime.getURL('saka.html')) {
      if (lastTabId) {
        try {
          const lastTab = await browser.tabs.get(lastTabId);
          if (lastTab) {
            try {
              await browser.tabs.update(lastTabId, { active: true });
              if (SAKA_DEBUG) console.log(`Switched to tab ${lastTab.url}`);
            } catch (e) {
              if (SAKA_DEBUG)
github lusakasa / saka / src / background_page / index.js View on Github external
console.warn(
            `Failed to execute Saka into tab. Instead, created new Saka tab after ${
              currentTab.url
            }`
          );
      }
    }
    // If tab couldn't be found (e.g. because query was made from devtools) create a new tab
  } else {
    await browser.tabs.create({
      url: '/saka.html'
    });
    if (SAKA_DEBUG)
      console.log("Couldn't find tab. Instead, created new Saka tab.");
  }
  const window = await browser.windows.getLastFocused();
  await browser.windows.update(window.id, { focused: true });
  if (SAKA_DEBUG) console.groupEnd();
}
github ipfs-shipyard / ipfs-companion / add-on / src / lib / ipfs-companion.js View on Github external
badgeColor = '#418B8E'
      badgeIcon = '/icons/ipfs-logo-on.svg'
    } else if (state.peerCount === 0) {
      // API is online but no peers
      badgeColor = 'red'
      badgeIcon = '/icons/ipfs-logo-on.svg'
    } else {
      // API is offline
      badgeText = ''
      badgeColor = '#8C8C8C'
      badgeIcon = '/icons/ipfs-logo-off.svg'
    }
    try {
      const oldColor = colorArraytoHex(await browser.browserAction.getBadgeBackgroundColor({}))
      if (badgeColor !== oldColor) {
        await browser.browserAction.setBadgeBackgroundColor({ color: badgeColor })
        await setBrowserActionIcon(badgeIcon)
      }
      const oldText = await browser.browserAction.getBadgeText({})
      if (oldText !== badgeText) await browser.browserAction.setBadgeText({ text: badgeText })
    } catch (error) {
      console.error('Unable to update browserAction badge due to error', error)
    }
  }
github ipfs-shipyard / ipfs-companion / add-on / src / popup / browser-action / store.js View on Github external
.catch((err) => {
        console.error('runtime.openOptionsPage() failed, opening options page in tab instead.', err)
        // brave: fallback to opening options page as a tab.
        browser.tabs.create({ url: browser.extension.getURL('dist/options/options.html') })
      })
  })
github ipfs-shipyard / ipfs-companion / add-on / src / popup / browser-action / store.js View on Github external
requestAnimationFrame(async () => {
      const tabId = state.currentTab ? { tabId: state.currentTab.id } : null
      if (browser.pageAction && tabId && await browser.pageAction.isShown(tabId)) {
        // Get title stored on page load so that valid transport is displayed
        // even if user toggles between public/custom gateway after the load
        state.pageActionTitle = await browser.pageAction.getTitle(tabId)
        emitter.emit('render')
      }
    })
github acorn / twitter-bookmarks-search / pages / background.js View on Github external
import delay from "delay"
export default () => "Nothing to see, just a background script :)"

if (typeof window !== "undefined") {
  const browser = require("webextension-polyfill")

  // console.log("Hello from background script!")

  let tabId
  let authorization
  let csrfToken

  browser.webRequest.onSendHeaders.addListener(
    async details => {
      tabId = details.tabId
      authorization = details.requestHeaders.find(h => h.name.toLowerCase() === "authorization").value
      csrfToken = details.requestHeaders.find(h => h.name.toLowerCase() === "x-csrf-token").value

      sendCredentials()
    },
    { urls: ["*://*.twitter.com/*bookmark.json*"] },
    ["requestHeaders"]
  )

  async function sendCredentials() {
    let messageSent = false
    let tries = 0
    while (!messageSent && tries < 100) {
      try {
github toggl / toggl-button / src / scripts / settings.js View on Github external
dom.innerHTML = `<strong>${k}</strong> - ${TogglOrigins[customs[k]].name}`;
          li.appendChild(dom);

          dom = document.createElement('a');
          dom.className = 'remove-custom';
          dom.textContent = 'delete';
          li.appendChild(dom);

          customHtml.appendChild(li);
        }
      }

      replaceContent('#custom-perm-container', customHtml);

      // Load permissions list
      browser.permissions.getAll().then(function (results) {
        let key;

        try {
          Settings.origins = [];
          origins = results.origins;
          for (i = 0; i &lt; origins.length; i++) {
            name = url = origins[i]
              .replace('*://*.', '')
              .replace('*://', '')
              .replace('/*', '');
            if (url.split('.').length &gt; 2) {
              name = url.substr(url.indexOf('.') + 1);
            }
            Settings.origins[name] = {
              id: i,
              origin: origins[i],
github cnwangjie / better-onetab / src / common / tabs.js View on Github external
if (tabs.length === 0) return
  const lists = await storage.getLists()
  if (listIndex == null) {
    const newList = createNewTabList({tabs})
    if (opts.pinNewList) newList.pinned = true
    await listManager.addList(newList)
  } else {
    const list = lists[listIndex]
    tabs.forEach(tab =&gt; list.tabs.push(tab))
    await listManager.updateListById(list._id, _.pick(list, 'tabs'))
  }
  if (opts.addHistory) {
    for (let i = 0; i &lt; tabs.length; i += 1) {
      // maybe occur Error: "An unexpected error occurred" when trying to add about:* to history
      try {
        await browser.history.addUrl({url: tabs[i].url})
      } catch (e) {
        console.debug(`${tabs[i].url} cannot be added to history`)
      }
    }
  }
  return browser.tabs.remove(tabs.map(i =&gt; i.id))
}
github dessant / search-by-image / src / select / App.vue View on Github external
mounted: function() {
    this.snackbar = new MDCSnackbar(this.$refs.snackbar);
    this.snackbar.foundation_.autoDismissTimeoutMs_ = 31556952000; // 1 year
    this.snackbar.closeOnEscape = false;

    browser.runtime.onMessage.addListener(this.onMessage);
    browser.runtime.sendMessage({id: 'selectFrameId'});
  }
};