web-api-manager/background_scripts/bootstrap.js

79 lines
2.4 KiB
JavaScript
Raw Normal View History

2017-09-12 17:34:25 -05:00
/*jslint es6: true*/
2017-10-13 17:30:57 -05:00
/*global chrome, browser, window, URI*/
2017-09-12 17:34:25 -05:00
(function () {
2017-10-13 17:30:57 -05:00
const {packingLib, standards, storageLib} = window.WEB_API_MANAGER;
const rootObject = window.browser || window.chrome;
2017-09-12 17:34:25 -05:00
2017-10-13 17:30:57 -05:00
// Once loaded from storage, will be a mapping from regular expressions
// (or the default option, "(default)"), to an array of standards
// that should be blocked on matching domains.
let domainRules;
2017-09-12 17:34:25 -05:00
2017-10-13 17:30:57 -05:00
storageLib.get(function (loadedDomainRules) {
domainRules = loadedDomainRules;
});
rootObject.runtime.onMessage.addListener(function (request, sender, tab) {
const [label, data] = request;
// Listen for updates to the domain rules from the config page.
if (label === "rulesUpdate") {
domainRules = data;
2017-09-12 17:34:25 -05:00
}
2017-10-13 17:30:57 -05:00
});
2017-09-12 17:34:25 -05:00
2017-10-13 17:30:57 -05:00
const extractHostFromUrl = function (url) {
const uri = URI(url);
return uri.hostname();
};
const matchingUrlReduceFunction = function (domain, prev, next) {
if (prev) {
return prev;
}
const domainRegex = new RegExp(next);
if (domainRegex.test(domain)) {
return next;
}
return prev;
};
const requestFilter = {
urls: ["<all_urls>"],
types: ["main_frame", "sub_frame"]
2017-09-12 17:34:25 -05:00
};
2017-10-13 17:30:57 -05:00
const requestOptions = ["blocking", "responseHeaders"];
chrome.webRequest.onHeadersReceived.addListener(function (details) {
const url = details.url;
const hostName = extractHostFromUrl(url);
const defaultKey = "(default)";
// Decide which set of blocking rules to use, depending on the host
// of the URL being requested.
const matchingUrlReduceFunctionBound = matchingUrlReduceFunction.bind(undefined, hostName);
const matchingPattern = Object
.keys(domainRules)
.filter((aRule) => aRule !== defaultKey)
.sort()
.reduce(matchingUrlReduceFunctionBound, undefined);
const standardsToBlock = domainRules[matchingPattern || defaultKey];
const options = Object.keys(standards);
const packedValues = packingLib.pack(options, standardsToBlock);
details.responseHeaders.push({
name: "Set-Cookie",
value: `web-api-manager=${packedValues}`
});
2017-09-12 17:34:25 -05:00
2017-10-13 17:30:57 -05:00
return {
responseHeaders: details.responseHeaders
};
2017-10-13 17:30:57 -05:00
}, requestFilter, requestOptions);
2017-09-12 17:34:25 -05:00
}());