How to use the webextension-polyfill.webRequest function in webextension-polyfill

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 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 tasn / webext-signed-pages / src / background.js View on Github external
const listener = (details) => {
    // FIXME: Only filter pages that we care about, the rest can skip this.
    let filter = browser.webRequest.filterResponseData(details.requestId);
    let decoder = new TextDecoder('utf-8');

    filter.ondata = event => {
      const str = decoder.decode(event.data, {stream: true});

      const signature = extractSignature(str);

      processPage(str, signature, details.url, details.tabId);

      filter.write(event.data);
      filter.disconnect();
    }

    return {};
  }
github tasn / webext-signed-pages / src / background.js View on Github external
filter.ondata = event => {
      const str = decoder.decode(event.data, {stream: true});

      const signature = extractSignature(str);

      processPage(str, signature, details.url, details.tabId);

      filter.write(event.data);
      filter.disconnect();
    }

    return {};
  }

  browser.webRequest.onBeforeRequest.addListener(
    listener,
    {urls: [""], types: ["main_frame"]},
    ["blocking"]
  );

  // Load results from cache if the page is cached
  browser.webNavigation.onCommitted.addListener((details) => {
    if (details.url in statusCache) {
      updateBrowserAction(statusCache[details.url], details.tabId);
    } else if (getPubkey(patterns, details.url)) {
      // We should never get here, but if there are issues, at least show an icon indicating of that.
      updateBrowserAction(unsureSignature, details.tabId);
    }
  });
} else {
  browser.runtime.onMessage.addListener(
github ipfs-shipyard / ipfs-companion / add-on / src / lib / ipfs-companion.js View on Github external
function registerListeners () {
    const onBeforeSendInfoSpec = ['blocking', 'requestHeaders']
    if (browser.webRequest.OnBeforeSendHeadersOptions && 'EXTRA_HEADERS' in browser.webRequest.OnBeforeSendHeadersOptions) {
      // Chrome 72+  requires 'extraHeaders' for access to Referer header (used in cors whitelisting of webui)
      onBeforeSendInfoSpec.push('extraHeaders')
    }
    browser.webRequest.onBeforeSendHeaders.addListener(onBeforeSendHeaders, { urls: [''] }, onBeforeSendInfoSpec)
    browser.webRequest.onBeforeRequest.addListener(onBeforeRequest, { urls: [''] }, ['blocking'])
    browser.webRequest.onHeadersReceived.addListener(onHeadersReceived, { urls: [''] }, ['blocking', 'responseHeaders'])
    browser.webRequest.onErrorOccurred.addListener(onErrorOccurred, { urls: [''], types: ['main_frame'] })
    browser.webRequest.onCompleted.addListener(onCompleted, { urls: [''], types: ['main_frame'] })
    browser.storage.onChanged.addListener(onStorageChange)
    browser.webNavigation.onCommitted.addListener(onNavigationCommitted)
    browser.webNavigation.onDOMContentLoaded.addListener(onDOMContentLoaded)
    browser.tabs.onActivated.addListener(onActivatedTab)
    if (browser.windows) {
      browser.windows.onFocusChanged.addListener(onWindowFocusChanged)
    }
    browser.runtime.onMessage.addListener(onRuntimeMessage)
github wille / hsts-everywhere / src / background.js View on Github external
for (const rule of ignoreRules) {
    if (rule instanceof RegExp && rule.test(hostname) || rule === hostname) {
      return true; 
    }
  }

  return false;
}

browser.storage.onChanged.addListener(function(changes) {
  if (changes.blockHttp) {
    blockHttpDowngrades = changes.blockHttp.newValue;
  }
})

browser.webRequest.onBeforeRequest.addListener(
  function(details) {
    if (details.requestId in redirLoop) {
      if (blockHttpDowngrades) {
        console.log(
          'Cancelled http (id=' +
            details.requestId +
            ') redir-loop to \'' +
            details.url +
            '\' (you might want to allow http or else this will never succeed!)'
        );
        delete redirLoop[details.requestId];
      } else {
        console.log('Allowed http (id=' + details.requestId + ') to \'' + details.url);
      }

      return { cancel: blockHttpDowngrades };
github dessant / web-archives / src / background / main.js View on Github external
async function setRequestListeners() {
  if (targetEnv !== 'firefox') {
    return;
  }

  const {showPageAction} = await storage.get('showPageAction', 'sync');
  const hasListener = browser.webRequest.onCompleted.hasListener(
    requestCompletedCallback
  );

  if (showPageAction) {
    if (!hasListener) {
      browser.webRequest.onCompleted.addListener(requestCompletedCallback, {
        types: ['main_frame'],
        urls: ['http://*/*', 'https://*/*']
      });

      browser.webRequest.onErrorOccurred.addListener(requestErrorCallback, {
        types: ['main_frame'],
        urls: ['http://*/*', 'https://*/*']
      });
    }
  } else {
github Altruisto / altruisto / src / background / recognize-other-affiliates.js View on Github external
) {
        affiliateRedirectDetected = true
        if (
          isAltruistoLink(details.url) ||
          isAltruistoLink(details.redirectUrl)
        ) {
          altruistoRedirectDetected = true
        } else {
          redirectTabId = currentTab
        }
      }
    },
    { urls: [""], types: ["main_frame"] }
  )

  browser.webRequest.onCompleted.addListener(
    function(details) {
      var currentTab = details.tabId

      if (affiliateRedirectDetected && !altruistoRedirectDetected) {
        if (redirectTabId == currentTab) {
          disableAffiliate(extractDomain(details.url))

          //reset triggers
          affiliateRedirectDetected = false
          altruistoRedirectDetected = false
          redirectTabId = 0
        }
      } else if (affiliateRedirectDetected && altruistoRedirectDetected) {
        //reset triggers
        affiliateRedirectDetected = false
        altruistoRedirectDetected = false
github dessant / buster / src / background / main.js View on Github external
!browser.webRequest.onBeforeRequest.hasListener(challengeRequestCallback)
    ) {
      browser.webRequest.onBeforeRequest.addListener(
        challengeRequestCallback,
        {
          urls: [
            'https://www.google.com/recaptcha/api2/anchor*',
            'https://www.google.com/recaptcha/api2/bframe*'
          ],
          types: ['sub_frame']
        },
        ['blocking']
      );
    }
  } else if (
    browser.webRequest.onBeforeRequest.hasListener(challengeRequestCallback)
  ) {
    browser.webRequest.onBeforeRequest.removeListener(challengeRequestCallback);
  }
}
github FirefoxBar / HeaderEditor / src / background.js View on Github external
initHook() {
		browser.webRequest.onBeforeRequest.addListener(this.handleBeforeRequest.bind(this), { urls: [""] }, ['blocking']);
		browser.webRequest.onBeforeSendHeaders.addListener(this.handleBeforeSend.bind(this), { urls: [""] }, utils.createHeaderListener('requestHeaders'));
		browser.webRequest.onHeadersReceived.addListener(this.handleReceived.bind(this), { urls: [""] }, utils.createHeaderListener('responseHeaders'));
	}
github dessant / buster / src / background / main.js View on Github external
browser.webRequest.onBeforeRequest.addListener(
        challengeRequestCallback,
        {
          urls: [
            'https://www.google.com/recaptcha/api2/anchor*',
            'https://www.google.com/recaptcha/api2/bframe*'
          ],
          types: ['sub_frame']
        },
        ['blocking']
      );
    }
  } else if (
    browser.webRequest.onBeforeRequest.hasListener(challengeRequestCallback)
  ) {
    browser.webRequest.onBeforeRequest.removeListener(challengeRequestCallback);
  }
}