import message handling code from uBO, simplify for uMatrix

pull/2/head
gorhill 7 years ago
parent 16eceedbf5
commit fa2658cd2b
No known key found for this signature in database
GPG Key ID: 25E1490B761470C2

@ -414,7 +414,7 @@ vAPI.setIcon = function(tabId, iconId, badge) {
/******************************************************************************/ /******************************************************************************/
vAPI.messaging = { vAPI.messaging = {
ports: {}, ports: new Map(),
listeners: {}, listeners: {},
defaultHandler: null, defaultHandler: null,
NOOPFUNC: noopFunc, NOOPFUNC: noopFunc,
@ -429,62 +429,114 @@ vAPI.messaging.listen = function(listenerName, callback) {
/******************************************************************************/ /******************************************************************************/
vAPI.messaging.onPortMessage = function(request, port) { vAPI.messaging.onPortMessage = (function() {
var callback = vAPI.messaging.NOOPFUNC; var messaging = vAPI.messaging;
if ( request.requestId !== undefined ) {
callback = CallbackWrapper.factory(port, request).callback;
}
// Specific handler // Use a wrapper to avoid closure and to allow reuse.
var r = vAPI.messaging.UNHANDLED; var CallbackWrapper = function(port, request) {
var listener = vAPI.messaging.listeners[request.channelName]; this.callback = this.proxy.bind(this); // bind once
if ( typeof listener === 'function' ) { this.init(port, request);
r = listener(request.msg, port.sender, callback); };
}
if ( r !== vAPI.messaging.UNHANDLED ) {
return;
}
// Default handler CallbackWrapper.prototype = {
r = vAPI.messaging.defaultHandler(request.msg, port.sender, callback); init: function(port, request) {
if ( r !== vAPI.messaging.UNHANDLED ) { this.port = port;
return; this.request = request;
} return this;
},
proxy: function(response) {
// https://github.com/chrisaljoudi/uBlock/issues/383
if ( messaging.ports.has(this.port.name) ) {
this.port.postMessage({
auxProcessId: this.request.auxProcessId,
channelName: this.request.channelName,
msg: response !== undefined ? response : null
});
}
// Mark for reuse
this.port = this.request = null;
callbackWrapperJunkyard.push(this);
}
};
console.error('µMatrix> messaging > unknown request: %o', request); var callbackWrapperJunkyard = [];
// Unhandled: var callbackWrapperFactory = function(port, request) {
// Need to callback anyways in case caller expected an answer, or var wrapper = callbackWrapperJunkyard.pop();
// else there is a memory leak on caller's side if ( wrapper ) {
callback(); return wrapper.init(port, request);
}; }
return new CallbackWrapper(port, request);
};
// https://bugzilla.mozilla.org/show_bug.cgi?id=1392067
// Workaround: manually remove ports matching removed tab.
chrome.tabs.onRemoved.addListener(function(tabId) {
for ( var port of messaging.ports.values() ) {
var tab = port.sender && port.sender.tab;
if ( !tab ) { continue; }
if ( tab.id === tabId ) {
vAPI.messaging.onPortDisconnect(port);
}
}
});
return function(request, port) {
// prepare response
var callback = this.NOOPFUNC;
if ( request.auxProcessId !== undefined ) {
callback = callbackWrapperFactory(port, request).callback;
}
// Auxiliary process to main process: specific handler
var r = this.UNHANDLED,
listener = this.listeners[request.channelName];
if ( typeof listener === 'function' ) {
r = listener(request.msg, port.sender, callback);
}
if ( r !== this.UNHANDLED ) { return; }
// Auxiliary process to main process: default handler
r = this.defaultHandler(request.msg, port.sender, callback);
if ( r !== this.UNHANDLED ) { return; }
// Auxiliary process to main process: no handler
console.error(
'vAPI.messaging.onPortMessage > unhandled request: %o',
request
);
// Need to callback anyways in case caller expected an answer, or
// else there is a memory leak on caller's side
callback();
}.bind(vAPI.messaging);
})();
/******************************************************************************/ /******************************************************************************/
vAPI.messaging.onPortDisconnect = function(port) { vAPI.messaging.onPortDisconnect = function(port) {
port.onDisconnect.removeListener(vAPI.messaging.onPortDisconnect); port.onDisconnect.removeListener(this.onPortDisconnect);
port.onMessage.removeListener(vAPI.messaging.onPortMessage); port.onMessage.removeListener(this.onPortMessage);
delete vAPI.messaging.ports[port.name]; this.ports.delete(port.name);
}; }.bind(vAPI.messaging);
/******************************************************************************/ /******************************************************************************/
vAPI.messaging.onPortConnect = function(port) { vAPI.messaging.onPortConnect = function(port) {
port.onDisconnect.addListener(vAPI.messaging.onPortDisconnect); port.onDisconnect.addListener(this.onPortDisconnect);
port.onMessage.addListener(vAPI.messaging.onPortMessage); port.onMessage.addListener(this.onPortMessage);
vAPI.messaging.ports[port.name] = port; this.ports.set(port.name, port);
}; }.bind(vAPI.messaging);
/******************************************************************************/ /******************************************************************************/
vAPI.messaging.setup = function(defaultHandler) { vAPI.messaging.setup = function(defaultHandler) {
// Already setup? if ( this.defaultHandler !== null ) { return; }
if ( this.defaultHandler !== null ) {
return;
}
if ( typeof defaultHandler !== 'function' ) { if ( typeof defaultHandler !== 'function' ) {
defaultHandler = function(){ return vAPI.messaging.UNHANDLED; }; defaultHandler = function(){
return vAPI.messaging.UNHANDLED;
};
} }
this.defaultHandler = defaultHandler; this.defaultHandler = defaultHandler;
@ -498,69 +550,9 @@ vAPI.messaging.broadcast = function(message) {
broadcast: true, broadcast: true,
msg: message msg: message
}; };
for ( var port of this.ports.values() ) {
for ( var portName in this.ports ) { port.postMessage(messageWrapper);
if ( this.ports.hasOwnProperty(portName) === false ) {
continue;
}
this.ports[portName].postMessage(messageWrapper);
}
};
/******************************************************************************/
// This allows to avoid creating a closure for every single message which
// expects an answer. Having a closure created each time a message is processed
// has been always bothering me. Another benefit of the implementation here
// is to reuse the callback proxy object, so less memory churning.
//
// https://developers.google.com/speed/articles/optimizing-javascript
// "Creating a closure is significantly slower then creating an inner
// function without a closure, and much slower than reusing a static
// function"
//
// http://hacksoflife.blogspot.ca/2015/01/the-four-horsemen-of-performance.html
// "the dreaded 'uniformly slow code' case where every function takes 1%
// of CPU and you have to make one hundred separate performance optimizations
// to improve performance at all"
//
// http://jsperf.com/closure-no-closure/2
var CallbackWrapper = function(port, request) {
// No need to bind every single time
this.callback = this.proxy.bind(this);
this.messaging = vAPI.messaging;
this.init(port, request);
};
CallbackWrapper.junkyard = [];
CallbackWrapper.factory = function(port, request) {
var wrapper = CallbackWrapper.junkyard.pop();
if ( wrapper ) {
wrapper.init(port, request);
return wrapper;
}
return new CallbackWrapper(port, request);
};
CallbackWrapper.prototype.init = function(port, request) {
this.port = port;
this.request = request;
};
CallbackWrapper.prototype.proxy = function(response) {
// https://github.com/chrisaljoudi/uBlock/issues/383
if ( this.messaging.ports.hasOwnProperty(this.port.name) ) {
this.port.postMessage({
requestId: this.request.requestId,
channelName: this.request.channelName,
msg: response !== undefined ? response : null
});
} }
// Mark for reuse
this.port = this.request = null;
CallbackWrapper.junkyard.push(this);
}; };
/******************************************************************************/ /******************************************************************************/

@ -45,8 +45,8 @@ if ( vAPI.vapiClientInjected ) {
} }
vAPI.vapiClientInjected = true; vAPI.vapiClientInjected = true;
vAPI.sessionId = String.fromCharCode(Date.now() % 25 + 97) + vAPI.sessionId = String.fromCharCode(Date.now() % 26 + 97) +
Math.random().toString(36).slice(2); Math.random().toString(36).slice(2);
vAPI.chrome = true; vAPI.chrome = true;
/******************************************************************************/ /******************************************************************************/
@ -74,101 +74,159 @@ vAPI.shutdown = (function() {
/******************************************************************************/ /******************************************************************************/
var messagingConnector = function(response) { vAPI.messaging = {
if ( !response ) { port: null,
return; portTimer: null,
} portTimerDelay: 10000,
listeners: new Set(),
var channels = vAPI.messaging.channels; pending: new Map(),
var channel, listener; auxProcessId: 1,
shuttingDown: false,
if ( response.broadcast === true && !response.channelName ) {
for ( channel in channels ) { shutdown: function() {
if ( channels.hasOwnProperty(channel) === false ) { this.shuttingDown = true;
continue; this.destroyPort();
} },
listener = channels[channel].listener;
if ( typeof listener === 'function' ) {
listener(response.msg);
}
}
return;
}
if ( response.requestId ) {
listener = vAPI.messaging.listeners[response.requestId];
delete vAPI.messaging.listeners[response.requestId];
delete response.requestId;
}
if ( !listener ) { disconnectListener: function() {
channel = channels[response.channelName]; this.port = null;
listener = channel && channel.listener; vAPI.shutdown.exec();
} },
disconnectListenerBound: null,
if ( typeof listener === 'function' ) { messageListener: function(details) {
listener(response.msg); if ( !details ) { return; }
}
};
/******************************************************************************/ // Sent to all listeners
if ( details.broadcast ) {
this.sendToListeners(details.msg);
return;
}
vAPI.messaging = { // Response to specific message previously sent
port: null, var listener;
channels: {}, if ( details.auxProcessId ) {
listeners: {}, listener = this.pending.get(details.auxProcessId);
requestId: 1, if ( listener !== undefined ) {
this.pending.delete(details.auxProcessId);
listener(details.msg);
return;
}
}
},
messageListenerCallback: null,
portPoller: function() {
this.portTimer = null;
if (
this.port !== null &&
this.listeners.size === 0 &&
this.pending.size === 0
) {
return this.destroyPort();
}
this.portTimer = vAPI.setTimeout(this.portPollerBound, this.portTimerDelay);
this.portTimerDelay = Math.min(this.portTimerDelay * 2, 60 * 60 * 1000);
},
portPollerBound: null,
setup: function() { destroyPort: function() {
this.port = chrome.runtime.connect({name: vAPI.sessionId}); if ( this.portTimer !== null ) {
this.port.onMessage.addListener(messagingConnector); clearTimeout(this.portTimer);
this.portTimer = null;
}
var port = this.port;
if ( port !== null ) {
port.disconnect();
port.onMessage.removeListener(this.messageListenerCallback);
port.onDisconnect.removeListener(this.disconnectListenerBound);
this.port = null;
}
this.listeners.clear();
// service pending callbacks
if ( this.pending.size !== 0 ) {
var pending = this.pending;
this.pending = new Map();
for ( var callback of pending.values() ) {
if ( typeof callback === 'function' ) {
callback(null);
}
}
}
}, },
close: function() { createPort: function() {
if ( this.port === null ) { if ( this.shuttingDown ) { return null; }
return; if ( this.messageListenerCallback === null ) {
this.messageListenerCallback = this.messageListener.bind(this);
this.disconnectListenerBound = this.disconnectListener.bind(this);
this.portPollerBound = this.portPoller.bind(this);
} }
this.port.disconnect(); try {
this.port.onMessage.removeListener(messagingConnector); this.port = chrome.runtime.connect({name: vAPI.sessionId}) || null;
this.port = null; } catch (ex) {
this.channels = {}; this.port = null;
this.listeners = {}; }
if ( this.port !== null ) {
this.port.onMessage.addListener(this.messageListenerCallback);
this.port.onDisconnect.addListener(this.disconnectListenerBound);
this.portTimerDelay = 10000;
if ( this.portTimer === null ) {
this.portTimer = vAPI.setTimeout(
this.portPollerBound,
this.portTimerDelay
);
}
}
return this.port;
},
getPort: function() {
return this.port !== null ? this.port : this.createPort();
}, },
channel: function(channelName, callback) { send: function(channelName, message, callback) {
if ( !channelName ) { // Too large a gap between the last request and the last response means
// the main process is no longer reachable: memory leaks and bad
// performance become a risk -- especially for long-lived, dynamic
// pages. Guard against this.
if ( this.pending.size > 25 ) {
vAPI.shutdown.exec();
}
var port = this.getPort();
if ( port === null ) {
if ( typeof callback === 'function' ) { callback(); }
return; return;
} }
var auxProcessId;
this.channels[channelName] = { if ( callback ) {
auxProcessId = this.auxProcessId++;
this.pending.set(auxProcessId, callback);
}
port.postMessage({
channelName: channelName, channelName: channelName,
listener: typeof callback === 'function' ? callback : null, auxProcessId: auxProcessId,
send: function(message, callback) { msg: message
if ( vAPI.messaging.port === null ) { });
vAPI.messaging.setup(); },
}
message = { addListener: function(listener) {
channelName: this.channelName, this.listeners.add(listener);
msg: message this.getPort();
}; },
if ( callback ) { removeListener: function(listener) {
message.requestId = vAPI.messaging.requestId++; this.listeners.delete(listener);
vAPI.messaging.listeners[message.requestId] = callback; },
}
vAPI.messaging.port.postMessage(message); removeAllListeners: function() {
}, this.listeners.clear();
close: function() { },
delete vAPI.messaging.channels[this.channelName];
if ( Object.keys(vAPI.messaging.channels).length === 0 ) {
vAPI.messaging.close();
}
}
};
return this.channels[channelName]; sendToListeners: function(msg) {
for ( var listener of this.listeners ) {
listener(msg);
}
} }
}; };
@ -191,6 +249,6 @@ vAPI.setTimeout = vAPI.setTimeout || function(callback, delay) {
/******************************************************************************/ /******************************************************************************/
})(this); })(this); // jshint ignore: line
/******************************************************************************/ /******************************************************************************/

@ -1,7 +1,7 @@
/******************************************************************************* /*******************************************************************************
µMatrix - a Chromium browser extension to black/white list requests. uMatrix - a Chromium browser extension to black/white list requests.
Copyright (C) 2014 Raymond Hill Copyright (C) 2014-2017 Raymond Hill
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -19,7 +19,7 @@
Home: https://github.com/gorhill/uMatrix Home: https://github.com/gorhill/uMatrix
*/ */
/* global vAPI, uDom */ /* global uDom */
'use strict'; 'use strict';
@ -29,10 +29,6 @@ uDom.onLoad(function() {
/******************************************************************************/ /******************************************************************************/
var messager = vAPI.messaging.channel('about.js');
/******************************************************************************/
var backupUserDataToFile = function() { var backupUserDataToFile = function() {
var userDataReady = function(userData) { var userDataReady = function(userData) {
vAPI.download({ vAPI.download({
@ -41,7 +37,7 @@ var backupUserDataToFile = function() {
}); });
}; };
messager.send({ what: 'getAllUserData' }, userDataReady); vAPI.messaging.send('about.js', { what: 'getAllUserData' }, userDataReady);
}; };
/******************************************************************************/ /******************************************************************************/
@ -58,12 +54,14 @@ function restoreUserDataFromFile() {
if ( userData === null ) { if ( userData === null ) {
return null; return null;
} }
if ( typeof userData !== 'object' || if (
typeof userData.version !== 'string' || typeof userData !== 'object' ||
typeof userData.when !== 'number' || typeof userData.version !== 'string' ||
typeof userData.settings !== 'object' || typeof userData.when !== 'number' ||
typeof userData.rules !== 'string' || typeof userData.settings !== 'object' ||
typeof userData.hostsFiles !== 'object' ) { typeof userData.rules !== 'string' ||
typeof userData.hostsFiles !== 'object'
) {
return null; return null;
} }
return userData; return userData;
@ -80,7 +78,10 @@ function restoreUserDataFromFile() {
.replace('{{time}}', time.toLocaleString()); .replace('{{time}}', time.toLocaleString());
var proceed = window.confirm(msg); var proceed = window.confirm(msg);
if ( proceed ) { if ( proceed ) {
messager.send({ what: 'restoreAllUserData', userData: userData }); vAPI.messaging.send(
'about.js',
{ what: 'restoreAllUserData', userData: userData }
);
} }
}; };
@ -112,7 +113,7 @@ var startRestoreFilePicker = function() {
var resetUserData = function() { var resetUserData = function() {
var proceed = window.confirm(uDom('[data-i18n="aboutResetConfirm"]').text()); var proceed = window.confirm(uDom('[data-i18n="aboutResetConfirm"]').text());
if ( proceed ) { if ( proceed ) {
messager.send({ what: 'resetAllUserData' }); vAPI.messaging.send('about.js', { what: 'resetAllUserData' });
} }
}; };
@ -129,7 +130,7 @@ var resetUserData = function() {
document.getElementById('aboutStorageUsed').textContent = document.getElementById('aboutStorageUsed').textContent =
template.replace('{{storageUsed}}', storageUsed); template.replace('{{storageUsed}}', storageUsed);
}; };
messager.send({ what: 'getSomeStats' }, renderStats); vAPI.messaging.send('about.js', { what: 'getSomeStats' }, renderStats);
})(); })();
/******************************************************************************/ /******************************************************************************/

@ -19,34 +19,27 @@
Home: https://github.com/gorhill/uMatrix Home: https://github.com/gorhill/uMatrix
*/ */
/* global uDom */
'use strict'; 'use strict';
/******************************************************************************/ /******************************************************************************/
(function() { (function() {
/******************************************************************************/ var onAssetContentReceived = function(details) {
document.getElementById('content').textContent =
var messager = vAPI.messaging.channel('asset-viewer.js'); details && (details.content || '');
};
/******************************************************************************/
var q = window.location.search;
var onAssetContentReceived = function(details) { var matches = q.match(/^\?url=([^&]+)/);
document.getElementById('content').textContent = details && (details.content || ''); if ( !matches || matches.length !== 2 ) {
}; return;
}
/******************************************************************************/
vAPI.messaging.send(
var q = window.location.search; 'asset-viewer.js',
var matches = q.match(/^\?url=([^&]+)/); { what : 'getAssetContent', url: matches[1] },
if ( !matches || matches.length !== 2 ) { onAssetContentReceived
return; );
}
messager.send({ what : 'getAssetContent', url: matches[1] }, onAssetContentReceived);
/******************************************************************************/
})(); })();

@ -1,7 +1,7 @@
/******************************************************************************* /*******************************************************************************
uBlock Origin - a browser extension to block requests. uBlock Origin - a browser extension to block requests.
Copyright (C) 2015 Raymond Hill Copyright (C) 2015-2017 Raymond Hill
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
@ -20,6 +20,7 @@
*/ */
/* global uDom */ /* global uDom */
'use strict'; 'use strict';
/******************************************************************************/ /******************************************************************************/
@ -50,10 +51,6 @@ if ( self.cloud.datakey === '' ) {
/******************************************************************************/ /******************************************************************************/
var messager = vAPI.messaging.channel('cloud-ui.js');
/******************************************************************************/
var onCloudDataReceived = function(entry) { var onCloudDataReceived = function(entry) {
if ( typeof entry !== 'object' || entry === null ) { if ( typeof entry !== 'object' || entry === null ) {
return; return;
@ -84,7 +81,8 @@ var onCloudDataReceived = function(entry) {
/******************************************************************************/ /******************************************************************************/
var fetchCloudData = function() { var fetchCloudData = function() {
messager.send( vAPI.messaging.send(
'cloud-ui.js',
{ {
what: 'cloudPull', what: 'cloudPull',
datakey: self.cloud.datakey datakey: self.cloud.datakey
@ -99,7 +97,8 @@ var pushData = function() {
if ( typeof self.cloud.onPush !== 'function' ) { if ( typeof self.cloud.onPush !== 'function' ) {
return; return;
} }
messager.send( vAPI.messaging.send(
'cloud-ui.js',
{ {
what: 'cloudPush', what: 'cloudPush',
datakey: self.cloud.datakey, datakey: self.cloud.datakey,
@ -154,7 +153,7 @@ var submitOptions = function() {
self.cloud.options = options; self.cloud.options = options;
}; };
messager.send({ vAPI.messaging.send('cloud-ui.js', {
what: 'cloudSetOptions', what: 'cloudSetOptions',
options: { options: {
deviceName: uDom.nodeFromId('cloudDeviceName').value deviceName: uDom.nodeFromId('cloudDeviceName').value
@ -205,7 +204,7 @@ var onInitialize = function(options) {
xhr.send(); xhr.send();
}; };
messager.send({ what: 'cloudGetOptions' }, onInitialize); vAPI.messaging.send('cloud-ui.js', { what: 'cloudGetOptions' }, onInitialize);
/******************************************************************************/ /******************************************************************************/

@ -19,8 +19,7 @@
Home: https://github.com/gorhill/uMatrix Home: https://github.com/gorhill/uMatrix
*/ */
/* global HTMLDocument, vAPI */ /* global HTMLDocument */
/* jshint multistr: true */
'use strict'; 'use strict';
@ -58,14 +57,6 @@ if ( vAPI.contentscriptEndInjected ) {
} }
vAPI.contentscriptEndInjected = true; vAPI.contentscriptEndInjected = true;
/******************************************************************************/
var localMessager = vAPI.messaging.channel('contentscript.js');
vAPI.shutdown.add(function() {
localMessager.close();
});
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/
@ -88,9 +79,9 @@ vAPI.shutdown.add(function() {
var hasLocalStorage = window.localStorage && window.localStorage.length; var hasLocalStorage = window.localStorage && window.localStorage.length;
var hasSessionStorage = window.sessionStorage && window.sessionStorage.length; var hasSessionStorage = window.sessionStorage && window.sessionStorage.length;
if ( hasLocalStorage || hasSessionStorage ) { if ( hasLocalStorage || hasSessionStorage ) {
localMessager.send({ vAPI.messaging.send('contentscript.js', {
what: 'contentScriptHasLocalStorage', what: 'contentScriptHasLocalStorage',
url: window.location.href url: window.location.href
}, localStorageHandler); }, localStorageHandler);
} }
@ -214,7 +205,7 @@ var collapser = (function() {
var send = function() { var send = function() {
timer = null; timer = null;
localMessager.send({ vAPI.messaging.send('contentscript.js', {
what: 'evaluateURLs', what: 'evaluateURLs',
requests: newRequests requests: newRequests
}, onProcessed); }, onProcessed);
@ -397,7 +388,7 @@ var nodeListsAddedHandler = function(nodeLists) {
collapser.addBranches(nodeLists[i]); collapser.addBranches(nodeLists[i]);
} }
if ( summary.mustReport ) { if ( summary.mustReport ) {
localMessager.send(summary); vAPI.messaging.send('contentscript.js', summary);
} }
collapser.process(); collapser.process();
}; };
@ -422,7 +413,7 @@ var nodeListsAddedHandler = function(nodeLists) {
//console.debug('contentscript.js > firstObservationHandler(): found %d script tags in "%s"', Object.keys(summary.scriptSources).length, window.location.href); //console.debug('contentscript.js > firstObservationHandler(): found %d script tags in "%s"', Object.keys(summary.scriptSources).length, window.location.href);
localMessager.send(summary); vAPI.messaging.send('contentscript.js', summary);
collapser.addNodes(document.querySelectorAll('iframe,img')); collapser.addNodes(document.querySelectorAll('iframe,img'));
collapser.process(); collapser.process();
@ -539,17 +530,25 @@ var nodeListsAddedHandler = function(nodeLists) {
} }
}; };
localMessager.send({ what: 'mustRenderNoscriptTags?' }, renderNoscriptTags); vAPI.messaging.send(
'contentscript.js',
{ what: 'mustRenderNoscriptTags?' },
renderNoscriptTags
);
})(); })();
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/
localMessager.send({ what: 'shutdown?' }, function(response) { vAPI.messaging.send(
if ( response === true ) { 'contentscript.js',
vAPI.shutdown.exec(); { what: 'shutdown?' },
function(response) {
if ( response === true ) {
vAPI.shutdown.exec();
}
} }
}); );
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/

@ -19,8 +19,6 @@
Home: https://github.com/gorhill/uMatrix Home: https://github.com/gorhill/uMatrix
*/ */
/* global µMatrix */
// rhill 2013-12-14: the whole cookie management has been rewritten so as // rhill 2013-12-14: the whole cookie management has been rewritten so as
// to avoid having to call chrome API whenever a single cookie changes, and // to avoid having to call chrome API whenever a single cookie changes, and
// to record cookie for a web page *only* when its value changes. // to record cookie for a web page *only* when its value changes.

@ -36,7 +36,7 @@ var listDetails = {},
/******************************************************************************/ /******************************************************************************/
var onMessage = function(msg) { vAPI.messaging.addListener(function onMessage(msg) {
switch ( msg.what ) { switch ( msg.what ) {
case 'assetUpdated': case 'assetUpdated':
updateAssetStatus(msg); updateAssetStatus(msg);
@ -50,9 +50,7 @@ var onMessage = function(msg) {
default: default:
break; break;
} }
}; });
var messager = vAPI.messaging.channel('hosts-files.js', onMessage);
/******************************************************************************/ /******************************************************************************/
@ -190,7 +188,7 @@ var renderHostsFiles = function(soft) {
renderWidgets(); renderWidgets();
}; };
messager.send({ what: 'getLists' }, onListsReceived); vAPI.messaging.send('hosts-files.js', { what: 'getLists' }, onListsReceived);
}; };
/******************************************************************************/ /******************************************************************************/
@ -274,7 +272,7 @@ var onPurgeClicked = function() {
listKey = liEntry.attr('data-listkey'); listKey = liEntry.attr('data-listkey');
if ( !listKey ) { return; } if ( !listKey ) { return; }
messager.send({ what: 'purgeCache', assetKey: listKey }); vAPI.messaging.send('hosts-files.js', { what: 'purgeCache', assetKey: listKey });
liEntry.addClass('obsolete'); liEntry.addClass('obsolete');
liEntry.removeClass('cached'); liEntry.removeClass('cached');
@ -311,7 +309,9 @@ var selectHostsFiles = function(callback) {
toImport = externalListsElem.value.trim(); toImport = externalListsElem.value.trim();
externalListsElem.value = ''; externalListsElem.value = '';
messager.send({ vAPI.messaging.send(
'hosts-files.js',
{
what: 'selectHostsFiles', what: 'selectHostsFiles',
toSelect: toSelect, toSelect: toSelect,
toImport: toImport, toImport: toImport,
@ -328,7 +328,7 @@ var selectHostsFiles = function(callback) {
var buttonApplyHandler = function() { var buttonApplyHandler = function() {
uDom('#buttonApply').removeClass('enabled'); uDom('#buttonApply').removeClass('enabled');
selectHostsFiles(function() { selectHostsFiles(function() {
messager.send({ what: 'reloadHostsFiles' }); vAPI.messaging.send('hosts-files.js', { what: 'reloadHostsFiles' });
}); });
renderWidgets(); renderWidgets();
}; };
@ -339,7 +339,7 @@ var buttonUpdateHandler = function() {
uDom('#buttonUpdate').removeClass('enabled'); uDom('#buttonUpdate').removeClass('enabled');
selectHostsFiles(function() { selectHostsFiles(function() {
document.body.classList.add('updating'); document.body.classList.add('updating');
messager.send({ what: 'forceUpdateAssets' }); vAPI.messaging.send('hosts-files.js', { what: 'forceUpdateAssets' });
renderWidgets(); renderWidgets();
}); });
renderWidgets(); renderWidgets();
@ -349,19 +349,26 @@ var buttonUpdateHandler = function() {
var buttonPurgeAllHandler = function() { var buttonPurgeAllHandler = function() {
uDom('#buttonPurgeAll').removeClass('enabled'); uDom('#buttonPurgeAll').removeClass('enabled');
messager.send({ what: 'purgeAllCaches' }, function() { vAPI.messaging.send(
renderHostsFiles(true); 'hosts-files.js',
}); { what: 'purgeAllCaches' },
function() {
renderHostsFiles(true);
}
);
}; };
/******************************************************************************/ /******************************************************************************/
var autoUpdateCheckboxChanged = function() { var autoUpdateCheckboxChanged = function() {
messager.send({ vAPI.messaging.send(
what: 'userSettings', 'hosts-files.js',
name: 'autoUpdate', {
value: this.checked what: 'userSettings',
}); name: 'autoUpdate',
value: this.checked
}
);
}; };
/******************************************************************************/ /******************************************************************************/

@ -19,17 +19,16 @@
Home: https://github.com/gorhill/sessbench Home: https://github.com/gorhill/sessbench
*/ */
/* global vAPI, uDom */ /* global uDom */
'use strict';
/******************************************************************************/ /******************************************************************************/
(function() { (function() {
'use strict';
/******************************************************************************/ /******************************************************************************/
var messager = vAPI.messaging.channel('logger-ui.js');
var tbody = document.querySelector('#content tbody'); var tbody = document.querySelector('#content tbody');
var trJunkyard = []; var trJunkyard = [];
var tdJunkyard = []; var tdJunkyard = [];
@ -61,16 +60,6 @@ document.getElementById('content').style.setProperty(
/******************************************************************************/ /******************************************************************************/
var escapeHTML = function(s) {
return s.replace(reEscapeLeftBracket, '<')
.replace(reEscapeRightBracket, '>');
};
var reEscapeLeftBracket = /</g;
var reEscapeRightBracket = />/g;
/******************************************************************************/
var classNameFromTabId = function(tabId) { var classNameFromTabId = function(tabId) {
if ( tabId === noTabId ) { if ( tabId === noTabId ) {
return 'tab_bts'; return 'tab_bts';
@ -377,7 +366,7 @@ var synchronizeTabIds = function(newTabIds) {
var select = document.getElementById('pageSelector'); var select = document.getElementById('pageSelector');
var selectValue = select.value; var selectValue = select.value;
var tabIds = Object.keys(newTabIds).sort(function(a, b) { var tabIds = Object.keys(newTabIds).sort(function(a, b) {
return newTabIds[a].localeCompare(newTabIds[a]); return newTabIds[a].localeCompare(newTabIds[b]);
}); });
var option; var option;
for ( var i = 0, j = 2; i < tabIds.length; i++ ) { for ( var i = 0, j = 2; i < tabIds.length; i++ ) {
@ -473,7 +462,7 @@ var onLogBufferRead = function(response) {
// require a bit more code to ensure no multi time out events. // require a bit more code to ensure no multi time out events.
var readLogBuffer = function() { var readLogBuffer = function() {
messager.send({ what: 'readMany' }, onLogBufferRead); vAPI.messaging.send('logger-ui.js', { what: 'readMany' }, onLogBufferRead);
}; };
/******************************************************************************/ /******************************************************************************/
@ -508,7 +497,10 @@ var refreshTab = function() {
if ( matches[1] === 'bts' ) { if ( matches[1] === 'bts' ) {
return; return;
} }
messager.send({ what: 'forceReloadTab', tabId: matches[1] }); vAPI.messaging.send(
'logger-ui.js',
{ what: 'forceReloadTab', tabId: matches[1] }
);
}; };
/******************************************************************************/ /******************************************************************************/
@ -524,7 +516,7 @@ var onMaxEntriesChanged = function() {
maxEntries = 0; maxEntries = 0;
} }
messager.send({ vAPI.messaging.send('logger-ui.js', {
what: 'userSettings', what: 'userSettings',
name: 'maxLoggedRequests', name: 'maxLoggedRequests',
value: maxEntries value: maxEntries

@ -21,12 +21,12 @@
/* global uDom */ /* global uDom */
'use strict';
/******************************************************************************/ /******************************************************************************/
(function() { (function() {
'use strict';
/******************************************************************************/ /******************************************************************************/
var details = {}; var details = {};
@ -157,9 +157,7 @@ if ( window.history.length > 1 ) {
// See if the target hostname is still blacklisted, and if not, navigate to it. // See if the target hostname is still blacklisted, and if not, navigate to it.
var messager = vAPI.messaging.channel('main-blocked.js'); vAPI.messaging.send('main-blocked.js', {
messager.send({
what: 'mustBlock', what: 'mustBlock',
scope: details.hn, scope: details.hn,
hostname: details.hn, hostname: details.hn,

@ -147,8 +147,6 @@ var expandosFromNode = function(node) {
return node; return node;
}; };
var messager = vAPI.messaging.channel('popup.js');
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/
@ -158,7 +156,7 @@ function getUserSetting(setting) {
function setUserSetting(setting, value) { function setUserSetting(setting, value) {
matrixSnapshot.userSettings[setting] = value; matrixSnapshot.userSettings[setting] = value;
messager.send({ vAPI.messaging.send('popup.js', {
what: 'userSettings', what: 'userSettings',
name: setting, name: setting,
value: value value: value
@ -518,7 +516,7 @@ function handleFilter(button, leaning) {
desHostname: desHostname, desHostname: desHostname,
type: type type: type
}; };
messager.send(request, updateMatrixSnapshot); vAPI.messaging.send('popup.js', request, updateMatrixSnapshot);
} }
function handleWhitelistFilter(button) { function handleWhitelistFilter(button) {
@ -1212,7 +1210,7 @@ function toggleMatrixSwitch(ev) {
switchName: switchName, switchName: switchName,
srcHostname: matrixSnapshot.scope srcHostname: matrixSnapshot.scope
}; };
messager.send(request, updateMatrixSnapshot); vAPI.messaging.send('popup.js', request, updateMatrixSnapshot);
} }
/******************************************************************************/ /******************************************************************************/
@ -1237,7 +1235,7 @@ function persistMatrix() {
what: 'applyDiffToPermanentMatrix', what: 'applyDiffToPermanentMatrix',
diff: matrixSnapshot.diff diff: matrixSnapshot.diff
}; };
messager.send(request, updateMatrixSnapshot); vAPI.messaging.send('popup.js', request, updateMatrixSnapshot);
} }
/******************************************************************************/ /******************************************************************************/
@ -1250,7 +1248,7 @@ function revertMatrix() {
what: 'applyDiffToTemporaryMatrix', what: 'applyDiffToTemporaryMatrix',
diff: matrixSnapshot.diff diff: matrixSnapshot.diff
}; };
messager.send(request, updateMatrixSnapshot); vAPI.messaging.send('popup.js', request, updateMatrixSnapshot);
} }
/******************************************************************************/ /******************************************************************************/
@ -1269,14 +1267,14 @@ function revertAll() {
var request = { var request = {
what: 'revertTemporaryMatrix' what: 'revertTemporaryMatrix'
}; };
messager.send(request, updateMatrixSnapshot); vAPI.messaging.send('popup.js', request, updateMatrixSnapshot);
dropDownMenuHide(); dropDownMenuHide();
} }
/******************************************************************************/ /******************************************************************************/
function buttonReloadHandler(ev) { function buttonReloadHandler(ev) {
messager.send({ vAPI.messaging.send('popup.js', {
what: 'forceReloadTab', what: 'forceReloadTab',
tabId: matrixSnapshot.tabId, tabId: matrixSnapshot.tabId,
bypassCache: ev.shiftKey bypassCache: ev.shiftKey
@ -1298,7 +1296,7 @@ function mouseleaveMatrixCellHandler() {
function gotoExtensionURL(ev) { function gotoExtensionURL(ev) {
var url = uDom(ev.currentTarget).attr('data-extension-url'); var url = uDom(ev.currentTarget).attr('data-extension-url');
if ( url ) { if ( url ) {
messager.send({ vAPI.messaging.send('popup.js', {
what: 'gotoExtensionURL', what: 'gotoExtensionURL',
url: url, url: url,
shiftKey: ev.shiftKey shiftKey: ev.shiftKey
@ -1406,7 +1404,7 @@ var matrixSnapshotPoller = (function() {
var pollNow = function() { var pollNow = function() {
unpollAsync(); unpollAsync();
messager.send({ vAPI.messaging.send('popup.js', {
what: 'matrixSnapshot', what: 'matrixSnapshot',
tabId: matrixSnapshot.tabId, tabId: matrixSnapshot.tabId,
scope: matrixSnapshot.scope, scope: matrixSnapshot.scope,
@ -1461,7 +1459,7 @@ var matrixSnapshotPoller = (function() {
pollAsync(); pollAsync();
}; };
messager.send({ vAPI.messaging.send('popup.js', {
what: 'matrixSnapshot', what: 'matrixSnapshot',
tabId: tabId tabId: tabId
}, snapshotFetched); }, snapshotFetched);

@ -19,8 +19,7 @@
Home: https://github.com/gorhill/uMatrix Home: https://github.com/gorhill/uMatrix
*/ */
/* global vAPI, uDom */ /* global uDom */
/* jshint multistr: true */
'use strict'; 'use strict';
@ -30,14 +29,12 @@
/******************************************************************************/ /******************************************************************************/
var messager = vAPI.messaging.channel('settings.js');
var cachedSettings = {}; var cachedSettings = {};
/******************************************************************************/ /******************************************************************************/
function changeUserSettings(name, value) { function changeUserSettings(name, value) {
messager.send({ vAPI.messaging.send('settings.js', {
what: 'userSettings', what: 'userSettings',
name: name, name: name,
value: value value: value
@ -47,7 +44,7 @@ function changeUserSettings(name, value) {
/******************************************************************************/ /******************************************************************************/
function changeMatrixSwitch(name, state) { function changeMatrixSwitch(name, state) {
messager.send({ vAPI.messaging.send('settings.js', {
what: 'setMatrixSwitch', what: 'setMatrixSwitch',
switchName: name, switchName: name,
state: state state: state
@ -149,7 +146,11 @@ uDom.onLoad(function() {
installEventHandlers(); installEventHandlers();
}; };
messager.send({ what: 'getUserSettings' }, onSettingsReceived); vAPI.messaging.send(
'settings.js',
{ what: 'getUserSettings' },
onSettingsReceived
);
}); });
/******************************************************************************/ /******************************************************************************/

@ -19,17 +19,13 @@
Home: https://github.com/gorhill/uMatrix Home: https://github.com/gorhill/uMatrix
*/ */
/* global vAPI, uDom */ /* global uDom */
/******************************************************************************/
(function() {
'use strict'; 'use strict';
/******************************************************************************/ /******************************************************************************/
var messager = vAPI.messaging.channel('user-rules.js'); (function() {
/******************************************************************************/ /******************************************************************************/
@ -190,7 +186,7 @@ var handleImportFilePicker = function() {
'what': 'setUserRules', 'what': 'setUserRules',
'temporaryRules': rulesFromHTML('#diff .right li') + '\n' + result 'temporaryRules': rulesFromHTML('#diff .right li') + '\n' + result
}; };
messager.send(request, processUserRules); vAPI.messaging.send('user-rules.js', request, processUserRules);
}; };
var file = this.files[0]; var file = this.files[0];
if ( file === undefined || file.name === '' ) { if ( file === undefined || file.name === '' ) {
@ -248,7 +244,7 @@ var revertHandler = function() {
'what': 'setUserRules', 'what': 'setUserRules',
'temporaryRules': rulesFromHTML('#diff .left li') 'temporaryRules': rulesFromHTML('#diff .left li')
}; };
messager.send(request, processUserRules); vAPI.messaging.send('user-rules.js', request, processUserRules);
}; };
/******************************************************************************/ /******************************************************************************/
@ -258,12 +254,12 @@ var commitHandler = function() {
'what': 'setUserRules', 'what': 'setUserRules',
'permanentRules': rulesFromHTML('#diff .right li') 'permanentRules': rulesFromHTML('#diff .right li')
}; };
messager.send(request, processUserRules); vAPI.messaging.send('user-rules.js', request, processUserRules);
}; };
/******************************************************************************/ /******************************************************************************/
var editStartHandler = function(ev) { var editStartHandler = function() {
uDom('#diff .right textarea').val(rulesFromHTML('#diff .right li')); uDom('#diff .right textarea').val(rulesFromHTML('#diff .right li'));
var parent = uDom(this).ancestors('#diff'); var parent = uDom(this).ancestors('#diff');
parent.toggleClass('edit', true); parent.toggleClass('edit', true);
@ -271,33 +267,33 @@ var editStartHandler = function(ev) {
/******************************************************************************/ /******************************************************************************/
var editStopHandler = function(ev) { var editStopHandler = function() {
var parent = uDom(this).ancestors('#diff'); var parent = uDom(this).ancestors('#diff');
parent.toggleClass('edit', false); parent.toggleClass('edit', false);
var request = { var request = {
'what': 'setUserRules', 'what': 'setUserRules',
'temporaryRules': uDom('#diff .right textarea').val() 'temporaryRules': uDom('#diff .right textarea').val()
}; };
messager.send(request, processUserRules); vAPI.messaging.send('user-rules.js', request, processUserRules);
}; };
/******************************************************************************/ /******************************************************************************/
var editCancelHandler = function(ev) { var editCancelHandler = function() {
var parent = uDom(this).ancestors('#diff'); var parent = uDom(this).ancestors('#diff');
parent.toggleClass('edit', false); parent.toggleClass('edit', false);
}; };
/******************************************************************************/ /******************************************************************************/
var temporaryRulesToggler = function(ev) { var temporaryRulesToggler = function() {
var li = uDom(this); var li = uDom(this);
li.toggleClass('toRemove'); li.toggleClass('toRemove');
var request = { var request = {
'what': 'setUserRules', 'what': 'setUserRules',
'temporaryRules': rulesFromHTML('#diff .right li') 'temporaryRules': rulesFromHTML('#diff .right li')
}; };
messager.send(request, processUserRules); vAPI.messaging.send('user-rules.js', request, processUserRules);
}; };
/******************************************************************************/ /******************************************************************************/
@ -315,7 +311,7 @@ self.cloud.onPull = function(data, append) {
'what': 'setUserRules', 'what': 'setUserRules',
'temporaryRules': data 'temporaryRules': data
}; };
messager.send(request, processUserRules); vAPI.messaging.send('user-rules.js', request, processUserRules);
}; };
/******************************************************************************/ /******************************************************************************/
@ -332,7 +328,7 @@ uDom.onLoad(function() {
uDom('#editCancelButton').on('click', editCancelHandler); uDom('#editCancelButton').on('click', editCancelHandler);
uDom('#diff > .right > ul').on('click', 'li', temporaryRulesToggler); uDom('#diff > .right > ul').on('click', 'li', temporaryRulesToggler);
messager.send({ what: 'getUserRules' }, processUserRules); vAPI.messaging.send('user-rules.js', { what: 'getUserRules' }, processUserRules);
}); });
/******************************************************************************/ /******************************************************************************/

Loading…
Cancel
Save