Files
webextensions-examples/dnr-redirect-url/popup.js
Rob Wu 06330a69c2 Add declarativeNetRequest (DNR) + MV3 examples (#526)
These examples are designed to be cross-browser compatible.
In particular, these extensions do not use `background` because there is
currently no single manifest that can support both Firefox and Chrome,
due to the lack of event page support in Chrome, and the lack of service
worker support in Firefox.

Three examples demonstrating the use of the declarativeNetRequest API:
- dnr-block-only: One minimal example demonstrating the use of static
  DNR rules to block requests.
- dnr-redirect-url: One minimal example demonstrating the use of static
  DNR rules to redirect requests.
- dnr-dynamic-with-options: A generic example demonstrating how host
  permissions can be requested and free forms to input DNR rules.
2023-05-17 18:13:55 +02:00

38 lines
1.3 KiB
JavaScript

"use strict";
if (typeof browser == "undefined") {
// `browser` is not defined in Chrome, but Manifest V3 extensions in Chrome
// also support promises in the `chrome` namespace, like Firefox. To easily
// test the example without modifications, polyfill "browser" to "chrome".
globalThis.browser = chrome;
}
const permissions = {
// This origin is listed in host_permissions:
origins: ["*://*.example.com/"],
};
const checkbox_host_permission = document.getElementById("checkbox_host_permission");
checkbox_host_permission.onchange = async () => {
if (checkbox_host_permission.checked) {
let granted = await browser.permissions.request(permissions);
if (!granted) {
// Permission request was denied by the user.
checkbox_host_permission.checked = false;
}
} else {
try {
await browser.permissions.remove(permissions);
} catch (e) {
// While Chrome allows granting of host_permissions that have manually
// been revoked by the user, it fails when revoking them, with
// "Error: You cannot remove required permissions."
console.error(e);
checkbox_host_permission.checked = true;
}
}
};
browser.permissions.contains(permissions).then(granted => {
checkbox_host_permission.checked = granted;
});