1
0
mirror of https://github.com/gorhill/uBlock.git synced 2024-10-04 08:37:11 +02:00

this takes care of #1443

This commit is contained in:
gorhill 2016-03-06 10:51:06 -05:00
parent 2c2dbfeb5e
commit eb8c17d55c
24 changed files with 1137 additions and 1210 deletions

View File

@ -1,7 +1,7 @@
/******************************************************************************* /*******************************************************************************
µBlock - a browser extension to block requests. uBlock Origin - a browser extension to block requests.
Copyright (C) 2014 The µBlock authors Copyright (C) 2014-2016 The µBlock authors
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
@ -29,6 +29,7 @@
'use strict'; 'use strict';
/******************************************************************************/
/******************************************************************************/ /******************************************************************************/
// https://github.com/chrisaljoudi/uBlock/issues/464 // https://github.com/chrisaljoudi/uBlock/issues/464
@ -91,241 +92,251 @@ vAPI.shutdown = (function() {
}; };
})(); })();
/******************************************************************************/
/******************************************************************************/ /******************************************************************************/
vAPI.messaging = { vAPI.messaging = {
port: null, port: null,
channels: {}, portTimer: null,
pending: {}, portTimerDelay: 10000,
channels: Object.create(null),
channelCount: 0,
pending: Object.create(null),
pendingCount: 0, pendingCount: 0,
auxProcessId: 1, auxProcessId: 1,
shuttingDown: false,
onDisconnect: function() { shutdown: function() {
this.shuttingDown = true;
this.destroyPort();
},
disconnectListener: function() {
this.port = null; this.port = null;
this.close();
vAPI.shutdown.exec(); vAPI.shutdown.exec();
}, },
disconnectListenerCallback: null,
setup: function() { messageListener: function(details) {
try { if ( !details ) {
this.port = chrome.runtime.connect({name: vAPI.sessionId}) || null; return;
} catch (ex) {
} }
if ( this.port === null ) {
vAPI.shutdown.exec(); // Sent to all channels
return false; if ( details.broadcast === true && !details.channelName ) {
for ( var channelName in this.channels ) {
this.sendToChannelListeners(channelName, details.msg);
}
return;
}
// Response to specific message previously sent
if ( details.auxProcessId ) {
var listener = this.pending[details.auxProcessId];
delete this.pending[details.auxProcessId];
delete details.auxProcessId; // TODO: why?
if ( listener ) {
this.pendingCount -= 1;
listener(details.msg);
return;
}
}
// Sent to a specific channel
var response = this.sendToChannelListeners(details.channelName, details.msg);
// Respond back if required
if ( details.mainProcessId === undefined ) {
return;
}
var port = this.connect();
if ( port !== null ) {
port.postMessage({
mainProcessId: details.mainProcessId,
msg: response
});
} }
this.port.onMessage.addListener(messagingConnector);
this.port.onDisconnect.addListener(this.onDisconnect.bind(this));
return true;
}, },
messageListenerCallback: null,
close: function() { portPoller: function() {
this.portTimer = null;
if ( this.port !== null ) {
if ( this.channelCount !== 0 || this.pendingCount !== 0 ) {
this.portTimer = vAPI.setTimeout(this.portPollerCallback, this.portTimerDelay);
this.portTimerDelay = Math.min(this.portTimerDelay * 2, 3600000);
return;
}
}
this.destroyPort();
},
portPollerCallback: null,
destroyPort: function() {
if ( this.portTimer !== null ) {
clearTimeout(this.portTimer);
this.portTimer = null;
}
var port = this.port; var port = this.port;
if ( port !== null ) { if ( port !== null ) {
port.disconnect(); port.disconnect();
port.onMessage.removeListener(messagingConnector); port.onMessage.removeListener(this.messageListenerCallback);
port.onDisconnect.removeListener(this.onDisconnect); port.onDisconnect.removeListener(this.disconnectListenerCallback);
this.port = null; this.port = null;
} }
this.channels = {}; if ( this.channelCount !== 0 ) {
this.channels = Object.create(null);
this.channelCount = 0;
}
// service pending callbacks // service pending callbacks
var pending = this.pending, listener; if ( this.pendingCount !== 0 ) {
this.pending = {}; var pending = this.pending, callback;
this.pendingCount = 0; this.pending = Object.create(null);
for ( var auxId in pending ) { this.pendingCount = 0;
if ( this.pending.hasOwnProperty(auxId) ) { for ( var auxId in pending ) {
listener = pending[auxId]; callback = pending[auxId];
if ( typeof listener === 'function' ) { if ( typeof callback === 'function' ) {
listener(null); callback(null);
} }
} }
} }
}, },
channel: function(channelName, callback) { createPort: function() {
if ( !channelName ) { if ( this.shuttingDown ) {
return; return null;
} }
var channel = this.channels[channelName]; if ( this.messageListenerCallback === null ) {
if ( channel instanceof MessagingChannel ) { this.messageListenerCallback = this.messageListener.bind(this);
channel.addListener(callback); this.disconnectListenerCallback = this.disconnectListener.bind(this);
channel.refCount += 1; this.portPollerCallback = this.portPoller.bind(this);
} else {
channel = this.channels[channelName] = new MessagingChannel(channelName, callback);
} }
return channel; var port = null;
} try {
}; port = this.port = chrome.runtime.connect({name: vAPI.sessionId});
port.onMessage.addListener(this.messageListenerCallback);
/******************************************************************************/ port.onDisconnect.addListener(this.disconnectListenerCallback);
} catch (ex) {
var messagingConnector = function(details) {
if ( !details ) {
return;
}
var messaging = vAPI.messaging;
var channels = messaging.channels;
var channel;
// Sent to all channels
if ( details.broadcast === true && !details.channelName ) {
for ( channel in channels ) {
if ( channels[channel] instanceof MessagingChannel === false ) {
continue;
}
channels[channel].sendToListeners(details.msg);
} }
return; this.portTimerDelay = 15000;
} if ( this.portTimer === null ) {
this.portTimer = vAPI.setTimeout(this.portPollerCallback, this.portTimerDelay);
// Response to specific message previously sent
if ( details.auxProcessId ) {
var listener = messaging.pending[details.auxProcessId];
delete messaging.pending[details.auxProcessId];
delete details.auxProcessId; // TODO: why?
if ( listener ) {
messaging.pendingCount -= 1;
listener(details.msg);
return;
} }
} return port;
},
// Sent to a specific channel connect: function() {
var response; return this.port !== null ? this.port : this.createPort();
channel = channels[details.channelName]; },
if ( channel instanceof MessagingChannel ) {
response = channel.sendToListeners(details.msg);
}
// Respond back if required send: function(channelName, message, callback) {
if ( details.mainProcessId !== undefined ) { this.sendTo(channelName, message, undefined, undefined, callback);
messaging.port.postMessage({ },
mainProcessId: details.mainProcessId,
msg: response
});
}
};
/******************************************************************************/ sendTo: function(channelName, message, toTabId, toChannel, callback) {
// Too large a gap between the last request and the last response means
var MessagingChannel = function(name, listener) { // the main process is no longer reachable: memory leaks and bad
this.channelName = name; // performance become a risk -- especially for long-lived, dynamic
this.listeners = typeof listener === 'function' ? [listener] : []; // pages. Guard against this.
this.refCount = 1; if ( this.pendingCount > 25 ) {
if ( typeof listener === 'function' ) { vAPI.shutdown.exec();
var messaging = vAPI.messaging;
if ( messaging.port === null ) {
messaging.setup();
} }
} var port = this.connect();
}; if ( port === null ) {
MessagingChannel.prototype.send = function(message, callback) {
this.sendTo(message, undefined, undefined, callback);
};
MessagingChannel.prototype.sendTo = function(message, toTabId, toChannel, callback) {
var messaging = vAPI.messaging;
// 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 ( messaging.pendingCount > 25 ) {
//console.error('uBlock> Sigh. Main process is sulking. Will try to patch things up.');
messaging.close();
}
if ( messaging.port === null ) {
if ( messaging.setup() === false ) {
if ( typeof callback === 'function' ) { if ( typeof callback === 'function' ) {
callback(); callback();
} }
return; return;
} }
} var auxProcessId;
var auxProcessId; if ( callback ) {
if ( callback ) { auxProcessId = this.auxProcessId++;
auxProcessId = messaging.auxProcessId++; this.pending[auxProcessId] = callback;
messaging.pending[auxProcessId] = callback; this.pendingCount += 1;
messaging.pendingCount += 1;
}
messaging.port.postMessage({
channelName: this.channelName,
auxProcessId: auxProcessId,
toTabId: toTabId,
toChannel: toChannel,
msg: message
});
};
MessagingChannel.prototype.close = function() {
this.refCount -= 1;
if ( this.refCount !== 0 ) {
return;
}
var messaging = vAPI.messaging;
delete messaging.channels[this.channelName];
if ( Object.keys(messaging.channels).length === 0 ) {
messaging.close();
}
};
MessagingChannel.prototype.addListener = function(callback) {
if ( typeof callback !== 'function' ) {
return;
}
if ( this.listeners.indexOf(callback) !== -1 ) {
throw new Error('Duplicate listener.');
}
this.listeners.push(callback);
var messaging = vAPI.messaging;
if ( messaging.port === null ) {
messaging.setup();
}
};
MessagingChannel.prototype.removeListener = function(callback) {
if ( typeof callback !== 'function' ) {
return;
}
var pos = this.listeners.indexOf(callback);
if ( pos === -1 ) {
throw new Error('Listener not found.');
}
this.listeners.splice(pos, 1);
};
MessagingChannel.prototype.removeAllListeners = function() {
this.listeners = [];
};
MessagingChannel.prototype.sendToListeners = function(msg) {
var response;
var listeners = this.listeners;
for ( var i = 0, n = listeners.length; i < n; i++ ) {
response = listeners[i](msg);
if ( response !== undefined ) {
break;
} }
port.postMessage({
channelName: channelName,
auxProcessId: auxProcessId,
toTabId: toTabId,
toChannel: toChannel,
msg: message
});
},
addChannelListener: function(channelName, callback) {
if ( typeof callback !== 'function' ) {
return;
}
var listeners = this.channels[channelName];
if ( listeners !== undefined && listeners.indexOf(callback) !== -1 ) {
console.error('Duplicate listener on channel "%s"', channelName);
return;
}
if ( listeners === undefined ) {
this.channels[channelName] = [callback];
this.channelCount += 1;
} else {
listeners.push(callback);
}
this.connect();
},
removeChannelListener: function(channelName, callback) {
if ( typeof callback !== 'function' ) {
return;
}
var listeners = this.channels[channelName];
if ( listeners === undefined ) {
return;
}
var pos = this.listeners.indexOf(callback);
if ( pos === -1 ) {
console.error('Listener not found on channel "%s"', channelName);
return;
}
listeners.splice(pos, 1);
if ( listeners.length === 0 ) {
delete this.channels[channelName];
this.channelCount -= 1;
}
},
removeAllChannelListeners: function(channelName) {
var listeners = this.channels[channelName];
if ( listeners === undefined ) {
return;
}
delete this.channels[channelName];
this.channelCount -= 1;
},
sendToChannelListeners: function(channelName, msg) {
var listeners = this.channels[channelName];
if ( listeners === undefined ) {
return;
}
var response;
for ( var i = 0, n = listeners.length; i < n; i++ ) {
response = listeners[i](msg);
if ( response !== undefined ) {
break;
}
}
return response;
} }
return response;
}; };
/******************************************************************************/
vAPI.shutdown.add(function() {
vAPI.messaging.shutdown();
window.vAPI = null;
});
// https://www.youtube.com/watch?v=rT5zCHn0tsg // https://www.youtube.com/watch?v=rT5zCHn0tsg
// https://www.youtube.com/watch?v=E-jS4e3zacI // https://www.youtube.com/watch?v=E-jS4e3zacI
/******************************************************************************/ /******************************************************************************/
// No need to have vAPI client linger around after shutdown if
// we are not a top window (because element picker can still
// be injected in top window).
if ( window !== window.top ) {
vAPI.shutdown.add(function() {
vAPI = null;
});
}
/******************************************************************************/ /******************************************************************************/
})(this); })(this);

View File

@ -410,6 +410,7 @@ vAPI.storage = (function() {
if ( typeof callback === 'function' && reason === 0 ) { if ( typeof callback === 'function' && reason === 0 ) {
callback(result); callback(result);
} }
result = null;
}, },
handleError: function(error) { handleError: function(error) {
console.error('SQLite error ', error.result, error.message); console.error('SQLite error ', error.result, error.message);
@ -417,6 +418,7 @@ vAPI.storage = (function() {
if ( typeof callback === 'function' ) { if ( typeof callback === 'function' ) {
callback(null); callback(null);
} }
result = null;
} }
}); });
}; };

View File

@ -114,16 +114,53 @@ vAPI.shutdown = (function() {
/******************************************************************************/ /******************************************************************************/
vAPI.messaging = { vAPI.messaging = {
channels: {}, channels: Object.create(null),
pending: {}, channelCount: 0,
pending: Object.create(null),
pendingCount: 0, pendingCount: 0,
auxProcessId: 1, auxProcessId: 1,
connected: false, connected: false,
connector: function(msg) {
messagingConnector(JSON.parse(msg)); messageListener: function(msg) {
var details = JSON.parse(msg);
if ( !details ) {
return;
}
// Sent to all channels
if ( details.broadcast && !details.channelName ) {
for ( var channelName in this.channels ) {
this.sendToChannelListeners(channelName, details.msg);
}
return;
}
// Response to specific message previously sent
if ( details.auxProcessId ) {
var listener = this.pending[details.auxProcessId];
delete this.pending[details.auxProcessId];
delete details.auxProcessId; // TODO: why?
if ( listener ) {
this.pendingCount -= 1;
listener(details.msg);
return;
}
}
// Sent to a specific channel
var response = this.sendToChannelListeners(details.channelName, details.msg);
// Respond back if required
if ( details.mainProcessId === undefined ) {
return;
}
sendAsyncMessage('ublock0:background', {
mainProcessId: details.mainProcessId,
msg: response
});
}, },
builtinChannelHandler: function(msg) { builtinListener: function(msg) {
if ( msg.cmd === 'injectScript' ) { if ( msg.cmd === 'injectScript' ) {
// injectScript is not always present. // injectScript is not always present.
// - See contentObserver.initContentScripts in frameModule.js // - See contentObserver.initContentScripts in frameModule.js
@ -152,7 +189,7 @@ vAPI.messaging = {
} }
if ( msg.cmd === 'shutdownSandbox' ) { if ( msg.cmd === 'shutdownSandbox' ) {
vAPI.shutdown.exec(); vAPI.shutdown.exec();
vAPI.messaging.shutdown(); this.stop();
if ( typeof self.outerShutdown === 'function' ) { if ( typeof self.outerShutdown === 'function' ) {
outerShutdown(); outerShutdown();
} }
@ -160,53 +197,58 @@ vAPI.messaging = {
} }
}, },
setup: function() { toggleListener: function({type, persisted}) {
this.channels['vAPI'] = new MessagingChannel('vAPI', this.builtinChannelHandler); if ( type === 'pagehide' && !persisted ) {
window.addEventListener('pagehide', this.toggleListener, true); vAPI.shutdown.exec();
window.addEventListener('pageshow', this.toggleListener, true); this.stop();
if ( typeof self.outerShutdown === 'function' ) {
outerShutdown();
}
return;
}
if ( type === 'pagehide' ) {
this.disconnect();
} else /* if ( type === 'pageshow' ) */ {
this.connect();
}
},
toggleListenerCallback: null,
start: function() {
this.addChannelListener('vAPI', this.builtinListener.bind(this));
if ( this.toggleListenerCallback === null ) {
this.toggleListenerCallback = this.toggleListener.bind(this);
}
window.addEventListener('pagehide', this.toggleListenerCallback, true);
window.addEventListener('pageshow', this.toggleListenerCallback, true);
}, },
shutdown: function() { stop: function() {
this.close(); if ( this.toggleListenerCallback !== null ) {
window.removeEventListener('pagehide', this.toggleListener, true); window.removeEventListener('pagehide', this.toggleListenerCallback, true);
window.removeEventListener('pageshow', this.toggleListener, true); window.removeEventListener('pageshow', this.toggleListenerCallback, true);
vAPI.messaging = null; }
},
close: function() {
this.disconnect(); this.disconnect();
this.channels = {}; this.channels = Object.create(null);
this.channelCount = 0;
// service pending callbacks // service pending callbacks
var pending = this.pending, listener; var pending = this.pending, callback;
this.pending = {}; this.pending = Object.create(null);
this.pendingCount = 0; this.pendingCount = 0;
for ( var auxId in pending ) { for ( var auxId in pending ) {
if ( this.pending.hasOwnProperty(auxId) ) { if ( this.pending.hasOwnProperty(auxId) ) {
listener = pending[auxId]; callback = pending[auxId];
if ( typeof listener === 'function' ) { if ( typeof callback === 'function' ) {
listener(null); callback(null);
} }
} }
} }
}, },
channel: function(channelName, callback) {
if ( !channelName ) {
return;
}
var channel = this.channels[channelName];
if ( channel instanceof MessagingChannel ) {
channel.addListener(callback);
channel.refCount += 1;
} else {
channel = this.channels[channelName] = new MessagingChannel(channelName, callback);
}
return channel;
},
connect: function() { connect: function() {
if ( !this.connected ) { if ( !this.connected ) {
addMessageListener(this.connector); addMessageListener(this.messageListener.bind(this));
this.connected = true; this.connected = true;
} }
}, },
@ -218,185 +260,109 @@ vAPI.messaging = {
} }
}, },
toggleListener: function({type, persisted}) { send: function(channelName, message, callback) {
var me = vAPI.messaging; this.sendTo(channelName, message, undefined, undefined, callback);
if ( !me ) { },
return;
}
if ( type === 'pagehide' ) { sendTo: function(channelName, message, toTabId, toChannel, callback) {
if ( !persisted ) { if ( !this.connected ) {
vAPI.shutdown.exec(); if ( typeof callback === 'function' ) {
vAPI.messaging.shutdown(); callback();
if ( typeof self.outerShutdown === 'function' ) {
outerShutdown();
}
} }
me.disconnect();
return; return;
} }
// Too large a gap between the last request and the last response means
me.connect(); // 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.pendingCount > 25 ) {
/******************************************************************************/ vAPI.shutdown.exec();
var messagingConnector = function(details) {
if ( !details ) {
return;
}
var messaging = vAPI.messaging;
// Sandbox might have been shutdown
if ( !messaging ) {
return;
}
var channels = messaging.channels;
var channel;
// Sent to all channels
if ( details.broadcast && !details.channelName ) {
for ( channel in channels ) {
if ( channels[channel] instanceof MessagingChannel === false ) {
continue;
}
channels[channel].sendToListeners(details.msg);
} }
return; this.connect();
} var auxProcessId;
if ( callback ) {
// Response to specific message previously sent auxProcessId = this.auxProcessId++;
if ( details.auxProcessId ) { this.pending[auxProcessId] = callback;
var listener = messaging.pending[details.auxProcessId]; this.pendingCount += 1;
delete messaging.pending[details.auxProcessId];
delete details.auxProcessId; // TODO: why?
if ( listener ) {
messaging.pendingCount -= 1;
listener(details.msg);
return;
} }
}
// Sent to a specific channel
var response;
channel = channels[details.channelName];
if ( channel instanceof MessagingChannel ) {
response = channel.sendToListeners(details.msg);
}
// Respond back if required
if ( details.mainProcessId !== undefined ) {
sendAsyncMessage('ublock0:background', { sendAsyncMessage('ublock0:background', {
mainProcessId: details.mainProcessId, channelName: self._sandboxId_ + '|' + channelName,
msg: response auxProcessId: auxProcessId,
toTabId: toTabId,
toChannel: toChannel,
msg: message
}); });
} },
};
/******************************************************************************/ addChannelListener: function(channelName, callback) {
if ( typeof callback !== 'function' ) {
var MessagingChannel = function(name, callback) { return;
this.channelName = name;
this.listeners = typeof callback === 'function' ? [callback] : [];
this.refCount = 1;
if ( typeof callback === 'function' ) {
vAPI.messaging.connect();
}
};
MessagingChannel.prototype.send = function(message, callback) {
this.sendTo(message, undefined, undefined, callback);
};
MessagingChannel.prototype.sendTo = function(message, toTabId, toChannel, callback) {
var messaging = vAPI.messaging;
if ( !messaging ) {
if ( typeof callback === 'function' ) {
callback();
} }
return; var listeners = this.channels[channelName];
} if ( listeners !== undefined && listeners.indexOf(callback) !== -1 ) {
// Too large a gap between the last request and the last response means console.error('Duplicate listener on channel "%s"', channelName);
// the main process is no longer reachable: memory leaks and bad return;
// performance become a risk -- especially for long-lived, dynamic
// pages. Guard against this.
if ( messaging.pendingCount > 25 ) {
//console.error('uBlock> Sigh. Main process is sulking. Will try to patch things up.');
messaging.close();
}
messaging.connect();
var auxProcessId;
if ( callback ) {
auxProcessId = messaging.auxProcessId++;
messaging.pending[auxProcessId] = callback;
messaging.pendingCount += 1;
}
sendAsyncMessage('ublock0:background', {
channelName: self._sandboxId_ + '|' + this.channelName,
auxProcessId: auxProcessId,
toTabId: toTabId,
toChannel: toChannel,
msg: message
});
};
MessagingChannel.prototype.close = function() {
this.refCount -= 1;
if ( this.refCount !== 0 ) {
return;
}
delete vAPI.messaging.channels[this.channelName];
};
MessagingChannel.prototype.addListener = function(callback) {
if ( typeof callback !== 'function' ) {
return;
}
if ( this.listeners.indexOf(callback) !== -1 ) {
throw new Error('Duplicate listener.');
}
this.listeners.push(callback);
vAPI.messaging.connect();
};
MessagingChannel.prototype.removeListener = function(callback) {
if ( typeof callback !== 'function' ) {
return;
}
var pos = this.listeners.indexOf(callback);
if ( pos === -1 ) {
throw new Error('Listener not found.');
}
this.listeners.splice(pos, 1);
};
MessagingChannel.prototype.removeAllListeners = function() {
this.listeners = [];
};
MessagingChannel.prototype.sendToListeners = function(msg) {
var response;
var listeners = this.listeners;
for ( var i = 0, n = listeners.length; i < n; i++ ) {
response = listeners[i](msg);
if ( response !== undefined ) {
break;
} }
if ( listeners === undefined ) {
this.channels[channelName] = [callback];
this.channelCount += 1;
} else {
listeners.push(callback);
}
this.connect();
},
removeChannelListener: function(channelName, callback) {
if ( typeof callback !== 'function' ) {
return;
}
var listeners = this.channels[channelName];
if ( listeners === undefined ) {
return;
}
var pos = this.listeners.indexOf(callback);
if ( pos === -1 ) {
console.error('Listener not found on channel "%s"', channelName);
return;
}
listeners.splice(pos, 1);
if ( listeners.length === 0 ) {
delete this.channels[channelName];
this.channelCount -= 1;
}
},
removeAllChannelListeners: function(channelName) {
var listeners = this.channels[channelName];
if ( listeners === undefined ) {
return;
}
delete this.channels[channelName];
this.channelCount -= 1;
},
sendToChannelListeners: function(channelName, msg) {
var listeners = this.channels[channelName];
if ( listeners === undefined ) {
return;
}
var response;
for ( var i = 0, n = listeners.length; i < n; i++ ) {
response = listeners[i](msg);
if ( response !== undefined ) {
break;
}
}
return response;
} }
return response;
}; };
vAPI.messaging.start();
// https://www.youtube.com/watch?v=Cg0cmhjdiLs // https://www.youtube.com/watch?v=Cg0cmhjdiLs
/******************************************************************************/ /******************************************************************************/
vAPI.messaging.setup();
/******************************************************************************/
// No need to have vAPI client linger around after shutdown if // No need to have vAPI client linger around after shutdown if
// we are not a top window (because element picker can still // we are not a top window (because element picker can still
// be injected in top window). // be injected in top window).

View File

@ -1,7 +1,7 @@
/******************************************************************************* /*******************************************************************************
µBlock - a browser extension to block requests. uBlock Origin - a browser extension to block requests.
Copyright (C) 2014 Raymond Hill Copyright (C) 2014-2016 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/uBlock Home: https://github.com/gorhill/uBlock
*/ */
/* global vAPI, uDom, uBlockDashboard */ /* global uDom, uBlockDashboard */
/******************************************************************************/ /******************************************************************************/
@ -29,14 +29,11 @@
/******************************************************************************/ /******************************************************************************/
var messaging = vAPI.messaging;
var cachedUserFilters = ''; var cachedUserFilters = '';
/******************************************************************************/ /******************************************************************************/
var messager = vAPI.messaging.channel('1p-filters.js');
/******************************************************************************/
// This is to give a visual hint that the content of user blacklist has changed. // This is to give a visual hint that the content of user blacklist has changed.
function userFiltersChanged() { function userFiltersChanged() {
@ -56,13 +53,13 @@ function renderUserFilters() {
uDom.nodeFromId('userFilters').value = details.content; uDom.nodeFromId('userFilters').value = details.content;
userFiltersChanged(); userFiltersChanged();
}; };
messager.send({ what: 'readUserFilters' }, onRead); messaging.send('dashboard', { what: 'readUserFilters' }, onRead);
} }
/******************************************************************************/ /******************************************************************************/
function allFiltersApplyHandler() { function allFiltersApplyHandler() {
messager.send({ what: 'reloadAllFilters' }); messaging.send('dashboard', { what: 'reloadAllFilters' });
uDom('#userFiltersApply').prop('disabled', true ); uDom('#userFiltersApply').prop('disabled', true );
} }
@ -160,7 +157,7 @@ var applyChanges = function() {
what: 'writeUserFilters', what: 'writeUserFilters',
content: textarea.value content: textarea.value
}; };
messager.send(request, onWritten); messaging.send('dashboard', request, onWritten);
}; };
var revertChanges = function() { var revertChanges = function() {

View File

@ -1,7 +1,7 @@
/******************************************************************************* /*******************************************************************************
µBlock - a browser extension to block requests. uBlock Origin - a browser extension to block requests.
Copyright (C) 2014 Raymond Hill Copyright (C) 2014-2016 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/uBlock Home: https://github.com/gorhill/uBlock
*/ */
/* global vAPI, uDom */ /* global uDom */
/******************************************************************************/ /******************************************************************************/
@ -48,7 +48,7 @@ var onMessage = function(msg) {
case 'forceUpdateAssetsProgress': case 'forceUpdateAssetsProgress':
renderBusyOverlay(true, msg.progress); renderBusyOverlay(true, msg.progress);
if ( msg.done ) { if ( msg.done ) {
messager.send({ what: 'reloadAllFilters' }); messaging.send('dashboard', { what: 'reloadAllFilters' });
} }
break; break;
@ -57,7 +57,8 @@ var onMessage = function(msg) {
} }
}; };
var messager = vAPI.messaging.channel('3p-filters.js', onMessage); var messaging = vAPI.messaging;
messaging.addChannelListener('dashboard', onMessage);
/******************************************************************************/ /******************************************************************************/
@ -262,7 +263,7 @@ var renderFilterLists = function() {
renderBusyOverlay(details.manualUpdate, details.manualUpdateProgress); renderBusyOverlay(details.manualUpdate, details.manualUpdateProgress);
}; };
messager.send({ what: 'getLists' }, onListsReceived); messaging.send('dashboard', { what: 'getLists' }, onListsReceived);
}; };
/******************************************************************************/ /******************************************************************************/
@ -372,7 +373,7 @@ var onPurgeClicked = function() {
return; return;
} }
messager.send({ what: 'purgeCache', path: href }); messaging.send('dashboard', { what: 'purgeCache', path: href });
button.remove(); button.remove();
// If the cached version is purged, the installed version must be assumed // If the cached version is purged, the installed version must be assumed
@ -397,11 +398,14 @@ var onPurgeClicked = function() {
var selectFilterLists = function(callback) { var selectFilterLists = function(callback) {
// Cosmetic filtering switch // Cosmetic filtering switch
messager.send({ messaging.send(
what: 'userSettings', 'dashboard',
name: 'parseAllABPHideFilters', {
value: listDetails.cosmetic what: 'userSettings',
}); name: 'parseAllABPHideFilters',
value: listDetails.cosmetic
}
);
// Filter lists // Filter lists
var switches = []; var switches = [];
@ -415,10 +419,14 @@ var selectFilterLists = function(callback) {
}); });
} }
messager.send({ messaging.send(
what: 'selectFilterLists', 'dashboard',
switches: switches {
}, callback); what: 'selectFilterLists',
switches: switches
},
callback
);
}; };
/******************************************************************************/ /******************************************************************************/
@ -429,7 +437,7 @@ var buttonApplyHandler = function() {
renderBusyOverlay(true); renderBusyOverlay(true);
var onSelectionDone = function() { var onSelectionDone = function() {
messager.send({ what: 'reloadAllFilters' }); messaging.send('dashboard', { what: 'reloadAllFilters' });
}; };
selectFilterLists(onSelectionDone); selectFilterLists(onSelectionDone);
@ -446,7 +454,7 @@ var buttonUpdateHandler = function() {
renderBusyOverlay(true); renderBusyOverlay(true);
var onSelectionDone = function() { var onSelectionDone = function() {
messager.send({ what: 'forceUpdateAssets' }); messaging.send('dashboard', { what: 'forceUpdateAssets' });
}; };
selectFilterLists(onSelectionDone); selectFilterLists(onSelectionDone);
@ -467,17 +475,20 @@ var buttonPurgeAllHandler = function() {
renderFilterLists(); renderFilterLists();
}; };
messager.send({ what: 'purgeAllCaches' }, onCompleted); messaging.send('dashboard', { what: 'purgeAllCaches' }, onCompleted);
}; };
/******************************************************************************/ /******************************************************************************/
var autoUpdateCheckboxChanged = function() { var autoUpdateCheckboxChanged = function() {
messager.send({ messaging.send(
what: 'userSettings', 'dashboard',
name: 'autoUpdate', {
value: this.checked what: 'userSettings',
}); name: 'autoUpdate',
value: this.checked
}
);
}; };
/******************************************************************************/ /******************************************************************************/
@ -494,7 +505,11 @@ var renderExternalLists = function() {
uDom('#externalLists').val(details); uDom('#externalLists').val(details);
externalLists = details; externalLists = details;
}; };
messager.send({ what: 'userSettings', name: 'externalLists' }, onReceived); messaging.send(
'dashboard',
{ what: 'userSettings', name: 'externalLists' },
onReceived
);
}; };
/******************************************************************************/ /******************************************************************************/
@ -508,11 +523,14 @@ var externalListsChangeHandler = function() {
var externalListsApplyHandler = function() { var externalListsApplyHandler = function() {
externalLists = uDom.nodeFromId('externalLists').value; externalLists = uDom.nodeFromId('externalLists').value;
messager.send({ messaging.send(
what: 'userSettings', 'dashboard',
name: 'externalLists', {
value: externalLists what: 'userSettings',
}); name: 'externalLists',
value: externalLists
}
);
renderFilterLists(); renderFilterLists();
uDom('#externalListsApply').prop('disabled', true); uDom('#externalListsApply').prop('disabled', true);
}; };

View File

@ -29,15 +29,11 @@ uDom.onLoad(function() {
/******************************************************************************/ /******************************************************************************/
var messager = vAPI.messaging.channel('about.js');
/******************************************************************************/
var onAppDataReady = function(appData) { var onAppDataReady = function(appData) {
uDom('#aboutNameVer').text(appData.name + ' v' + appData.version); uDom('#aboutNameVer').text(appData.name + ' v' + appData.version);
}; };
messager.send({ what: 'getAppData' }, onAppDataReady); vAPI.messaging.send('dashboard', { what: 'getAppData' }, onAppDataReady);
/******************************************************************************/ /******************************************************************************/

View File

@ -1,7 +1,7 @@
/******************************************************************************* /*******************************************************************************
µBlock - a browser extension to block requests. uBlock Origin - a browser extension to block requests.
Copyright (C) 2014 Raymond Hill Copyright (C) 2014-2016 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,16 +19,13 @@
Home: https://github.com/gorhill/uBlock Home: https://github.com/gorhill/uBlock
*/ */
/* global vAPI, uDom */ /* global uDom */
'use strict';
/******************************************************************************/ /******************************************************************************/
(function() { (function() {
/******************************************************************************/ 'use strict';
var messager = vAPI.messaging.channel('asset-viewer.js');
/******************************************************************************/ /******************************************************************************/
@ -44,7 +41,8 @@ if ( !matches || matches.length !== 2 ) {
return; return;
} }
messager.send( vAPI.messaging.send(
'default',
{ {
what : 'getAssetContent', what : 'getAssetContent',
url: decodeURIComponent(matches[1]) url: decodeURIComponent(matches[1])

View File

@ -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-2016 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,12 +20,13 @@
*/ */
/* global uDom */ /* global uDom */
'use strict';
/******************************************************************************/ /******************************************************************************/
(function() { (function() {
'use strict';
/******************************************************************************/ /******************************************************************************/
self.cloud = { self.cloud = {
@ -48,9 +49,7 @@ if ( self.cloud.datakey === '' ) {
return; return;
} }
/******************************************************************************/ var messaging = vAPI.messaging;
var messager = vAPI.messaging.channel('cloud-ui.js');
/******************************************************************************/ /******************************************************************************/
@ -84,7 +83,8 @@ var onCloudDataReceived = function(entry) {
/******************************************************************************/ /******************************************************************************/
var fetchCloudData = function() { var fetchCloudData = function() {
messager.send( messaging.send(
'cloudWidget',
{ {
what: 'cloudPull', what: 'cloudPull',
datakey: self.cloud.datakey datakey: self.cloud.datakey
@ -99,7 +99,8 @@ var pushData = function() {
if ( typeof self.cloud.onPush !== 'function' ) { if ( typeof self.cloud.onPush !== 'function' ) {
return; return;
} }
messager.send( messaging.send(
'cloudWidget',
{ {
what: 'cloudPush', what: 'cloudPush',
datakey: self.cloud.datakey, datakey: self.cloud.datakey,
@ -154,12 +155,16 @@ var submitOptions = function() {
self.cloud.options = options; self.cloud.options = options;
}; };
messager.send({ messaging.send(
what: 'cloudSetOptions', 'cloudWidget',
options: { {
deviceName: uDom.nodeFromId('cloudDeviceName').value what: 'cloudSetOptions',
} options: {
}, onOptions); deviceName: uDom.nodeFromId('cloudDeviceName').value
}
},
onOptions
);
uDom.nodeFromId('cloudOptions').classList.remove('show'); uDom.nodeFromId('cloudOptions').classList.remove('show');
}; };
@ -203,7 +208,7 @@ var onInitialize = function(options) {
uDom('#cloudOptionsSubmit').on('click', submitOptions); uDom('#cloudOptionsSubmit').on('click', submitOptions);
}; };
messager.send({ what: 'cloudGetOptions' }, onInitialize); messaging.send('cloudWidget', { what: 'cloudGetOptions' }, onInitialize);
/******************************************************************************/ /******************************************************************************/

View File

@ -1,7 +1,7 @@
/******************************************************************************* /*******************************************************************************
µBlock - a browser extension to block requests. uBlock Origin - a browser extension to block requests.
Copyright (C) 2014 Raymond Hill Copyright (C) 2014-2016 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
@ -55,15 +55,6 @@ if ( vAPI.contentscriptEndInjected ) {
vAPI.contentscriptEndInjected = true; vAPI.contentscriptEndInjected = true;
vAPI.styles = vAPI.styles || []; vAPI.styles = vAPI.styles || [];
/******************************************************************************/
var messager = vAPI.messaging.channel('contentscript-end.js');
// https://github.com/gorhill/uMatrix/issues/144
vAPI.shutdown.add(function() {
messager.close();
});
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/
@ -83,6 +74,7 @@ var uBlockCollapser = (function() {
var src2ndProps = { var src2ndProps = {
'img': 'srcset' 'img': 'srcset'
}; };
var messaging = vAPI.messaging;
var PendingRequest = function(target, tagName, attr) { var PendingRequest = function(target, tagName, attr) {
this.id = requestId++; this.id = requestId++;
@ -143,12 +135,15 @@ var uBlockCollapser = (function() {
} }
} }
if ( selectors.length !== 0 ) { if ( selectors.length !== 0 ) {
messager.send({ messaging.send(
what: 'cosmeticFiltersInjected', 'contentscript',
type: 'net', {
hostname: window.location.hostname, what: 'cosmeticFiltersInjected',
selectors: selectors type: 'net',
}); hostname: window.location.hostname,
selectors: selectors
}
);
} }
// Renew map: I believe that even if all properties are deleted, an // Renew map: I believe that even if all properties are deleted, an
// object will still use more memory than a brand new one. // object will still use more memory than a brand new one.
@ -159,12 +154,15 @@ var uBlockCollapser = (function() {
var send = function() { var send = function() {
timer = null; timer = null;
messager.send({ messaging.send(
what: 'filterRequests', 'contentscript',
pageURL: window.location.href, {
pageHostname: window.location.hostname, what: 'filterRequests',
requests: newRequests pageURL: window.location.href,
}, onProcessed); pageHostname: window.location.hostname,
requests: newRequests
}, onProcessed
);
newRequests = []; newRequests = [];
}; };
@ -400,6 +398,7 @@ var uBlockCollapser = (function() {
}; };
checkStyleTags(); checkStyleTags();
var messaging = vAPI.messaging;
var queriedSelectors = {}; var queriedSelectors = {};
var injectedSelectors = {}; var injectedSelectors = {};
var lowGenericSelectors = []; var lowGenericSelectors = [];
@ -410,7 +409,9 @@ var uBlockCollapser = (function() {
var retrieveGenericSelectors = function() { var retrieveGenericSelectors = function() {
if ( lowGenericSelectors.length !== 0 || highGenerics === null ) { if ( lowGenericSelectors.length !== 0 || highGenerics === null ) {
//console.log('µBlock> ABP cosmetic filters: retrieving CSS rules using %d selectors', lowGenericSelectors.length); //console.log('µBlock> ABP cosmetic filters: retrieving CSS rules using %d selectors', lowGenericSelectors.length);
messager.send({ messaging.send(
'contentscript',
{
what: 'retrieveGenericCosmeticSelectors', what: 'retrieveGenericCosmeticSelectors',
pageURL: window.location.href, pageURL: window.location.href,
selectors: lowGenericSelectors, selectors: lowGenericSelectors,
@ -522,12 +523,15 @@ var uBlockCollapser = (function() {
vAPI.styles.push(style); vAPI.styles.push(style);
} }
hideElements(styleText); hideElements(styleText);
messager.send({ messaging.send(
what: 'cosmeticFiltersInjected', 'contentscript',
type: 'cosmetic', {
hostname: window.location.hostname, what: 'cosmeticFiltersInjected',
selectors: selectors type: 'cosmetic',
}); hostname: window.location.hostname,
selectors: selectors
}
);
//console.debug('µBlock> generic cosmetic filters: injecting %d CSS rules:', selectors.length, text); //console.debug('µBlock> generic cosmetic filters: injecting %d CSS rules:', selectors.length, text);
}; };
@ -850,7 +854,7 @@ var uBlockCollapser = (function() {
idsFromNodeList(selectNodes('[id]')); idsFromNodeList(selectNodes('[id]'));
classesFromNodeList(selectNodes('[class]')); classesFromNodeList(selectNodes('[class]'));
retrieveGenericSelectors(); retrieveGenericSelectors();
messager.send({ what: 'cosmeticFiltersActivated' }); messaging.send('contentscript', { what: 'cosmeticFiltersActivated' });
} }
}; };
@ -903,6 +907,12 @@ var uBlockCollapser = (function() {
if ( addedNodeListsTimer !== null ) { if ( addedNodeListsTimer !== null ) {
clearTimeout(addedNodeListsTimer); clearTimeout(addedNodeListsTimer);
} }
if ( removedNodeListsTimer !== null ) {
clearTimeout(removedNodeListsTimer);
}
if ( processHighHighGenericsTimer !== null ) {
clearTimeout(processHighHighGenericsTimer);
}
}); });
})(); })();
@ -970,20 +980,25 @@ var uBlockCollapser = (function() {
if ( window !== window.top ) { if ( window !== window.top ) {
return; return;
} }
var messaging = vAPI.messaging;
var onMouseClick = function(ev) { var onMouseClick = function(ev) {
var elem = ev.target; var elem = ev.target;
while ( elem !== null && elem.localName !== 'a' ) { while ( elem !== null && elem.localName !== 'a' ) {
elem = elem.parentElement; elem = elem.parentElement;
} }
messager.send({ messaging.send(
what: 'mouseClick', 'contentscript',
x: ev.clientX, {
y: ev.clientY, what: 'mouseClick',
url: elem !== null ? elem.href : '' x: ev.clientX,
}); y: ev.clientY,
url: elem !== null ? elem.href : ''
});
}; };
window.addEventListener('mousedown', onMouseClick, true); document.addEventListener('mousedown', onMouseClick, true);
// https://github.com/gorhill/uMatrix/issues/144 // https://github.com/gorhill/uMatrix/issues/144
vAPI.shutdown.add(function() { vAPI.shutdown.add(function() {

View File

@ -1,7 +1,7 @@
/******************************************************************************* /*******************************************************************************
µBlock - a browser extension to block requests. uBlock Origin - a browser extension to block requests.
Copyright (C) 2014 Raymond Hill Copyright (C) 2014-2016 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
@ -35,23 +35,17 @@
// This can happen // This can happen
if ( typeof vAPI !== 'object' ) { if ( typeof vAPI !== 'object' ) {
//console.debug('contentscript-start.js > vAPI not found');
return; return;
} }
// https://github.com/chrisaljoudi/uBlock/issues/456 // https://github.com/chrisaljoudi/uBlock/issues/456
// Already injected? // Already injected?
if ( vAPI.contentscriptStartInjected ) { if ( vAPI.contentscriptStartInjected ) {
//console.debug('contentscript-start.js > content script already injected');
return; return;
} }
vAPI.contentscriptStartInjected = true; vAPI.contentscriptStartInjected = true;
vAPI.styles = vAPI.styles || []; vAPI.styles = vAPI.styles || [];
/******************************************************************************/
var localMessager = vAPI.messaging.channel('contentscript-start.js');
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/
@ -166,7 +160,7 @@ var filteringHandler = function(details) {
// This is just to inform the background process that cosmetic filters were // This is just to inform the background process that cosmetic filters were
// actually injected. // actually injected.
if ( vAPI.styles.length !== styleTagCount ) { if ( vAPI.styles.length !== styleTagCount ) {
localMessager.send({ what: 'cosmeticFiltersActivated' }); vAPI.messaging.send('contentscript', { what: 'cosmeticFiltersActivated' });
} }
// https://github.com/chrisaljoudi/uBlock/issues/587 // https://github.com/chrisaljoudi/uBlock/issues/587
@ -174,9 +168,6 @@ var filteringHandler = function(details) {
// process was fully initialized. When this happens, pages won't be // process was fully initialized. When this happens, pages won't be
// cleaned right after browser launch. // cleaned right after browser launch.
vAPI.contentscriptStartInjected = details && details.ready; vAPI.contentscriptStartInjected = details && details.ready;
// Cleanup before leaving
localMessager.close();
}; };
/******************************************************************************/ /******************************************************************************/
@ -233,7 +224,8 @@ var hideElements = function(selectors) {
/******************************************************************************/ /******************************************************************************/
var url = window.location.href; var url = window.location.href;
localMessager.send( vAPI.messaging.send(
'contentscript',
{ {
what: 'retrieveDomainCosmeticSelectors', what: 'retrieveDomainCosmeticSelectors',
pageURL: url, pageURL: url,

View File

@ -29,7 +29,7 @@
/******************************************************************************/ /******************************************************************************/
var messager = vAPI.messaging.channel('document-blocked.js'); var messaging = vAPI.messaging;
var details = {}; var details = {};
(function() { (function() {
@ -82,11 +82,15 @@ var details = {};
uDom.nodeFromId('whyex').style.removeProperty('display'); uDom.nodeFromId('whyex').style.removeProperty('display');
}; };
messager.send({ messaging.send(
what: 'listsFromNetFilter', 'documentBlocked',
compiledFilter: details.fc, {
rawFilter: details.fs what: 'listsFromNetFilter',
}, onReponseReady); compiledFilter: details.fc,
rawFilter: details.fs
},
onReponseReady
);
})(); })();
/******************************************************************************/ /******************************************************************************/
@ -109,22 +113,30 @@ var proceedToURL = function() {
/******************************************************************************/ /******************************************************************************/
var proceedTemporary = function() { var proceedTemporary = function() {
messager.send({ messaging.send(
what: 'temporarilyWhitelistDocument', 'documentBlocked',
hostname: getTargetHostname() {
}, proceedToURL); what: 'temporarilyWhitelistDocument',
hostname: getTargetHostname()
},
proceedToURL
);
}; };
/******************************************************************************/ /******************************************************************************/
var proceedPermanent = function() { var proceedPermanent = function() {
messager.send({ messaging.send(
what: 'toggleHostnameSwitch', 'documentBlocked',
name: 'no-strict-blocking', {
hostname: getTargetHostname(), what: 'toggleHostnameSwitch',
deep: true, name: 'no-strict-blocking',
state: true hostname: getTargetHostname(),
}, proceedToURL); deep: true,
state: true
},
proceedToURL
);
}; };
/******************************************************************************/ /******************************************************************************/

View File

@ -1,7 +1,7 @@
/******************************************************************************* /*******************************************************************************
µMatrix - a browser extension to block requests. uBlock Origin - a browser extension to block requests.
Copyright (C) 2014 Raymond Hill Copyright (C) 2014-2016 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 */
/******************************************************************************/ /******************************************************************************/
@ -29,7 +29,7 @@
/******************************************************************************/ /******************************************************************************/
var messager = vAPI.messaging.channel('dyna-rules.js'); var messaging = vAPI.messaging;
/******************************************************************************/ /******************************************************************************/
@ -125,7 +125,7 @@ function handleImportFilePicker() {
'what': 'setSessionRules', 'what': 'setSessionRules',
'rules': rulesFromHTML('#diff .right li') + '\n' + result 'rules': rulesFromHTML('#diff .right li') + '\n' + result
}; };
messager.send(request, renderRules); messaging.send('dashboard', request, renderRules);
}; };
var file = this.files[0]; var file = this.files[0];
if ( file === undefined || file.name === '' ) { if ( file === undefined || file.name === '' ) {
@ -188,7 +188,7 @@ var revertHandler = function() {
'what': 'setSessionRules', 'what': 'setSessionRules',
'rules': rulesFromHTML('#diff .left li') 'rules': rulesFromHTML('#diff .left li')
}; };
messager.send(request, renderRules); messaging.send('dashboard', request, renderRules);
}; };
/******************************************************************************/ /******************************************************************************/
@ -198,7 +198,7 @@ var commitHandler = function() {
'what': 'setPermanentRules', 'what': 'setPermanentRules',
'rules': rulesFromHTML('#diff .right li') 'rules': rulesFromHTML('#diff .right li')
}; };
messager.send(request, renderRules); messaging.send('dashboard', request, renderRules);
}; };
/******************************************************************************/ /******************************************************************************/
@ -222,7 +222,7 @@ var editStopHandler = function() {
'what': 'setSessionRules', 'what': 'setSessionRules',
'rules': uDom('#diff .right textarea').val() 'rules': uDom('#diff .right textarea').val()
}; };
messager.send(request, renderRules); messaging.send('dashboard', request, renderRules);
}; };
/******************************************************************************/ /******************************************************************************/
@ -249,7 +249,7 @@ var setCloudData = function(data, append) {
'what': 'setSessionRules', 'what': 'setSessionRules',
'rules': data 'rules': data
}; };
messager.send(request, renderRules); messaging.send('dashboard', request, renderRules);
}; };
self.cloud.onPush = getCloudData; self.cloud.onPush = getCloudData;
@ -269,7 +269,7 @@ uDom('#diff > .pane.right > .rulesContainer').on('dblclick', editStartHandler);
uDom('#editStopButton').on('click', editStopHandler); uDom('#editStopButton').on('click', editStopHandler);
uDom('#editCancelButton').on('click', editCancelHandler); uDom('#editCancelButton').on('click', editCancelHandler);
messager.send({ what: 'getRules' }, renderRules); messaging.send('dashboard', { what: 'getRules' }, renderRules);
/******************************************************************************/ /******************************************************************************/

View File

@ -40,7 +40,7 @@ if ( typeof Map === undefined || Map.polyfill || typeof WeakMap === undefined )
/******************************************************************************/ /******************************************************************************/
var logger = self.logger; var logger = self.logger;
var messager = logger.messager; var messaging = vAPI.messaging;
var inspectedTabId = ''; var inspectedTabId = '';
var inspectedURL = ''; var inspectedURL = '';
@ -349,9 +349,9 @@ var startDialog = (function() {
ev.stopPropagation(); ev.stopPropagation();
if ( target.id === 'createCosmeticFilters' ) { if ( target.id === 'createCosmeticFilters' ) {
messager.send({ what: 'createUserFilter', filters: textarea.value }); messaging.send('loggerUI', { what: 'createUserFilter', filters: textarea.value });
// Force a reload for the new cosmetic filter(s) to take effect // Force a reload for the new cosmetic filter(s) to take effect
messager.send({ what: 'reloadTab', tabId: inspectedTabId }); messaging.send('loggerUI', { what: 'reloadTab', tabId: inspectedTabId });
return stop(); return stop();
} }
}; };
@ -386,26 +386,28 @@ var startDialog = (function() {
}; };
var showCommitted = function() { var showCommitted = function() {
messager.sendTo( messaging.sendTo(
'loggerUI',
{ {
what: 'showCommitted', what: 'showCommitted',
hide: hideSelectors.join(',\n'), hide: hideSelectors.join(',\n'),
unhide: unhideSelectors.join(',\n') unhide: unhideSelectors.join(',\n')
}, },
inspectedTabId, inspectedTabId,
'dom-inspector.js' 'domInspector'
); );
}; };
var showInteractive = function() { var showInteractive = function() {
messager.sendTo( messaging.sendTo(
'loggerUI',
{ {
what: 'showInteractive', what: 'showInteractive',
hide: hideSelectors.join(',\n'), hide: hideSelectors.join(',\n'),
unhide: unhideSelectors.join(',\n') unhide: unhideSelectors.join(',\n')
}, },
inspectedTabId, inspectedTabId,
'dom-inspector.js' 'domInspector'
); );
}; };
@ -422,10 +424,11 @@ var startDialog = (function() {
}); });
} }
} }
messager.sendTo( messaging.sendTo(
'loggerUI',
{ what: 'cookFilters', entries: entries }, { what: 'cookFilters', entries: entries },
inspectedTabId, inspectedTabId,
'dom-inspector.js', 'domInspector',
onCooked onCooked
); );
}; };
@ -476,7 +479,8 @@ var onClick = function(ev) {
// Toggle cosmetic filter // Toggle cosmetic filter
if ( target.classList.contains('filter') ) { if ( target.classList.contains('filter') ) {
messager.sendTo( messaging.sendTo(
'loggerUI',
{ {
what: 'toggleNodes', what: 'toggleNodes',
original: false, original: false,
@ -485,7 +489,7 @@ var onClick = function(ev) {
nid: '' nid: ''
}, },
inspectedTabId, inspectedTabId,
'dom-inspector.js' 'domInspector'
); );
uDom('[data-filter-id="' + target.getAttribute('data-filter-id') + '"]', inspector).toggleClass( uDom('[data-filter-id="' + target.getAttribute('data-filter-id') + '"]', inspector).toggleClass(
'off', 'off',
@ -494,7 +498,8 @@ var onClick = function(ev) {
} }
// Toggle node // Toggle node
else { else {
messager.sendTo( messaging.sendTo(
'loggerUI',
{ {
what: 'toggleNodes', what: 'toggleNodes',
original: true, original: true,
@ -503,7 +508,7 @@ var onClick = function(ev) {
nid: nidFromNode(target) nid: nidFromNode(target)
}, },
inspectedTabId, inspectedTabId,
'dom-inspector.js' 'domInspector'
); );
} }
@ -520,7 +525,8 @@ var onMouseOver = (function() {
var timerHandler = function() { var timerHandler = function() {
mouseoverTimer = null; mouseoverTimer = null;
messager.sendTo( messaging.sendTo(
'loggerUI',
{ {
what: 'highlightOne', what: 'highlightOne',
selector: selectorFromNode(mouseoverTarget), selector: selectorFromNode(mouseoverTarget),
@ -528,7 +534,7 @@ var onMouseOver = (function() {
scrollTo: true scrollTo: true
}, },
inspectedTabId, inspectedTabId,
'dom-inspector.js' 'domInspector'
); );
}; };
@ -603,13 +609,14 @@ var fetchDOMAsync = (function() {
var onTimeout = function() { var onTimeout = function() {
pollTimer = null; pollTimer = null;
messager.sendTo( messaging.sendTo(
'loggerUI',
{ {
what: 'domLayout', what: 'domLayout',
fingerprint: fingerprint fingerprint: fingerprint
}, },
inspectedTabId, inspectedTabId,
'dom-inspector.js', 'domInspector',
onFetched onFetched
); );
}; };
@ -633,11 +640,14 @@ var injectInspector = function() {
} }
inspectedTabId = tabId; inspectedTabId = tabId;
fingerprint = null; fingerprint = null;
messager.send({ messaging.send(
what: 'scriptlet', 'loggerUI',
tabId: tabId, {
scriptlet: 'dom-inspector' what: 'scriptlet',
}); tabId: tabId,
scriptlet: 'dom-inspector'
}
);
fetchDOMAsync(250); fetchDOMAsync(250);
}; };
@ -660,7 +670,12 @@ var injectInspectorAsync = function(delay) {
var shutdownInspector = function() { var shutdownInspector = function() {
if ( inspectedTabId !== '' ) { if ( inspectedTabId !== '' ) {
messager.sendTo({ what: 'shutdown' }, inspectedTabId, 'dom-inspector.js'); messaging.sendTo(
'loggerUI',
{ what: 'shutdown' },
inspectedTabId,
'domInspector'
);
} }
logger.removeAllChildren(domTree); logger.removeAllChildren(domTree);
if ( pollTimer !== null ) { if ( pollTimer !== null ) {
@ -682,13 +697,14 @@ var onTabIdChanged = function() {
/******************************************************************************/ /******************************************************************************/
var toggleHighlightMode = function() { var toggleHighlightMode = function() {
messager.sendTo( messaging.sendTo(
'loggerUI',
{ {
what: 'highlightMode', what: 'highlightMode',
invert: uDom.nodeFromSelector('#domInspector .permatoolbar .highlightMode').classList.toggle('invert') invert: uDom.nodeFromSelector('#domInspector .permatoolbar .highlightMode').classList.toggle('invert')
}, },
inspectedTabId, inspectedTabId,
'dom-inspector.js' 'domInspector'
); );
}; };
@ -696,10 +712,11 @@ var toggleHighlightMode = function() {
var revert = function() { var revert = function() {
uDom('#domTree .off').removeClass('off'); uDom('#domTree .off').removeClass('off');
messager.sendTo( messaging.sendTo(
'loggerUI',
{ what: 'resetToggledNodes' }, { what: 'resetToggledNodes' },
inspectedTabId, inspectedTabId,
'dom-inspector.js' 'domInspector'
); );
inspector.querySelector('.permatoolbar .revert').classList.add('disabled'); inspector.querySelector('.permatoolbar .revert').classList.add('disabled');
inspector.querySelector('.permatoolbar .commit').classList.add('disabled'); inspector.querySelector('.permatoolbar .commit').classList.add('disabled');

View File

@ -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-2016 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/uBlock Home: https://github.com/gorhill/uBlock
*/ */
/* global vAPI, uDom */ /* global uDom */
/******************************************************************************/ /******************************************************************************/
@ -30,7 +30,7 @@
/******************************************************************************/ /******************************************************************************/
var logger = self.logger = {}; var logger = self.logger = {};
var messager = logger.messager = vAPI.messaging.channel('logger-ui.js'); var messaging = vAPI.messaging;
/******************************************************************************/ /******************************************************************************/
@ -728,7 +728,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: 'readAll' }, onLogBufferRead); messaging.send('loggerUI', { what: 'readAll' }, onLogBufferRead);
}; };
/******************************************************************************/ /******************************************************************************/
@ -789,7 +789,7 @@ var reloadTab = function() {
if ( tabId === 'bts' || tabId === '' ) { if ( tabId === 'bts' || tabId === '' ) {
return; return;
} }
messager.send({ what: 'reloadTab', tabId: tabId }); messaging.send('loggerUI', { what: 'reloadTab', tabId: tabId });
}; };
/******************************************************************************/ /******************************************************************************/
@ -810,11 +810,14 @@ var onMaxEntriesChanged = function() {
input.value = maxEntries.toString(10); input.value = maxEntries.toString(10);
messager.send({ messaging.send(
what: 'userSettings', 'loggerUI',
name: 'requestLogMaxEntries', {
value: maxEntries what: 'userSettings',
}); name: 'requestLogMaxEntries',
value: maxEntries
}
);
truncateLog(maxEntries); truncateLog(maxEntries);
}; };
@ -877,12 +880,16 @@ var netFilteringManager = (function() {
}; };
var colorize = function() { var colorize = function() {
messager.send({ messaging.send(
what: 'getURLFilteringData', 'loggerUI',
context: selectValue('select.dynamic.origin'), {
urls: targetURLs, what: 'getURLFilteringData',
type: uglyTypeFromSelector('dynamic') context: selectValue('select.dynamic.origin'),
}, onColorsReady); urls: targetURLs,
type: uglyTypeFromSelector('dynamic')
},
onColorsReady
);
}; };
var parseStaticInputs = function() { var parseStaticInputs = function() {
@ -963,10 +970,13 @@ var netFilteringManager = (function() {
createdStaticFilters[value] = true; createdStaticFilters[value] = true;
if ( value !== '' ) { if ( value !== '' ) {
var d = new Date(); var d = new Date();
messager.send({ messaging.send(
what: 'createUserFilter', 'loggerUI',
filters: '! ' + d.toLocaleString() + ' ' + targetPageDomain + '\n' + value {
}); what: 'createUserFilter',
filters: '! ' + d.toLocaleString() + ' ' + targetPageDomain + '\n' + value
}
);
} }
updateWidgets(); updateWidgets();
return; return;
@ -974,12 +984,16 @@ var netFilteringManager = (function() {
// Save url filtering rule(s) // Save url filtering rule(s)
if ( target.id === 'saveRules' ) { if ( target.id === 'saveRules' ) {
messager.send({ messaging.send(
what: 'saveURLFilteringRules', 'loggerUI',
context: selectValue('select.dynamic.origin'), {
urls: targetURLs, what: 'saveURLFilteringRules',
type: uglyTypeFromSelector('dynamic') context: selectValue('select.dynamic.origin'),
}, colorize); urls: targetURLs,
type: uglyTypeFromSelector('dynamic')
},
colorize
);
return; return;
} }
@ -987,73 +1001,95 @@ var netFilteringManager = (function() {
// Remove url filtering rule // Remove url filtering rule
if ( tcl.contains('action') ) { if ( tcl.contains('action') ) {
messager.send({ messaging.send(
what: 'setURLFilteringRule', 'loggerUI',
context: selectValue('select.dynamic.origin'), {
url: target.getAttribute('data-url'), what: 'setURLFilteringRule',
type: uglyTypeFromSelector('dynamic'), context: selectValue('select.dynamic.origin'),
action: 0, url: target.getAttribute('data-url'),
persist: persist type: uglyTypeFromSelector('dynamic'),
}, colorize); action: 0,
persist: persist
},
colorize
);
return; return;
} }
// add "allow" url filtering rule // add "allow" url filtering rule
if ( tcl.contains('allow') ) { if ( tcl.contains('allow') ) {
messager.send({ messaging.send(
what: 'setURLFilteringRule', 'loggerUI',
context: selectValue('select.dynamic.origin'), {
url: target.parentNode.getAttribute('data-url'), what: 'setURLFilteringRule',
type: uglyTypeFromSelector('dynamic'), context: selectValue('select.dynamic.origin'),
action: 2, url: target.parentNode.getAttribute('data-url'),
persist: persist type: uglyTypeFromSelector('dynamic'),
}, colorize); action: 2,
persist: persist
},
colorize
);
return; return;
} }
// add "block" url filtering rule // add "block" url filtering rule
if ( tcl.contains('noop') ) { if ( tcl.contains('noop') ) {
messager.send({ messaging.send(
what: 'setURLFilteringRule', 'loggerUI',
context: selectValue('select.dynamic.origin'), {
url: target.parentNode.getAttribute('data-url'), what: 'setURLFilteringRule',
type: uglyTypeFromSelector('dynamic'), context: selectValue('select.dynamic.origin'),
action: 3, url: target.parentNode.getAttribute('data-url'),
persist: persist type: uglyTypeFromSelector('dynamic'),
}, colorize); action: 3,
persist: persist
},
colorize
);
return; return;
} }
// add "block" url filtering rule // add "block" url filtering rule
if ( tcl.contains('block') ) { if ( tcl.contains('block') ) {
messager.send({ messaging.send(
what: 'setURLFilteringRule', 'loggerUI',
context: selectValue('select.dynamic.origin'), {
url: target.parentNode.getAttribute('data-url'), what: 'setURLFilteringRule',
type: uglyTypeFromSelector('dynamic'), context: selectValue('select.dynamic.origin'),
action: 1, url: target.parentNode.getAttribute('data-url'),
persist: persist type: uglyTypeFromSelector('dynamic'),
}, colorize); action: 1,
persist: persist
},
colorize
);
return; return;
} }
// Force a reload of the tab // Force a reload of the tab
if ( tcl.contains('reload') ) { if ( tcl.contains('reload') ) {
messager.send({ messaging.send(
what: 'reloadTab', 'loggerUI',
tabId: targetTabId {
}); what: 'reloadTab',
tabId: targetTabId
}
);
return; return;
} }
// Hightlight corresponding element in target web page // Hightlight corresponding element in target web page
if ( tcl.contains('picker') ) { if ( tcl.contains('picker') ) {
messager.send({ messaging.send(
what: 'launchElementPicker', 'loggerUI',
tabId: targetTabId, {
targetURL: 'img\t' + targetURLs[0], what: 'launchElementPicker',
select: true tabId: targetTabId,
}); targetURL: 'img\t' + targetURLs[0],
select: true
}
);
return; return;
} }
}; };
@ -1306,10 +1342,14 @@ var netFilteringManager = (function() {
targetFrameHostname = targetRow.getAttribute('data-hn-frame') || ''; targetFrameHostname = targetRow.getAttribute('data-hn-frame') || '';
// We need the root domain names for best user experience. // We need the root domain names for best user experience.
messager.send({ messaging.send(
what: 'getDomainNames', 'loggerUI',
targets: [targetURLs[0], targetPageHostname, targetFrameHostname] {
}, fillDialog); what: 'getDomainNames',
targets: [targetURLs[0], targetPageHostname, targetFrameHostname]
},
fillDialog
);
}; };
var toggleOff = function() { var toggleOff = function() {
@ -1425,17 +1465,25 @@ var reverseLookupManager = (function() {
} }
if ( row.classList.contains('cat_net') ) { if ( row.classList.contains('cat_net') ) {
messager.send({ messaging.send(
what: 'listsFromNetFilter', 'loggerUI',
compiledFilter: row.getAttribute('data-filter') || '', {
rawFilter: rawFilter what: 'listsFromNetFilter',
}, reverseLookupDone); compiledFilter: row.getAttribute('data-filter') || '',
rawFilter: rawFilter
},
reverseLookupDone
);
} else if ( row.classList.contains('cat_cosmetic') ) { } else if ( row.classList.contains('cat_cosmetic') ) {
messager.send({ messaging.send(
what: 'listsFromCosmeticFilter', 'loggerUI',
hostname: row.getAttribute('data-hn-frame') || '', {
rawFilter: rawFilter, what: 'listsFromCosmeticFilter',
}, reverseLookupDone); hostname: row.getAttribute('data-hn-frame') || '',
rawFilter: rawFilter,
},
reverseLookupDone
);
} }
}; };

View File

@ -128,6 +128,10 @@ var onMessage = function(request, sender, callback) {
response = getDomainNames(request.targets); response = getDomainNames(request.targets);
break; break;
case 'getWhitelist':
response = µb.stringFromWhitelist(µb.netWhitelist);
break;
case 'launchElementPicker': case 'launchElementPicker':
// Launched from some auxiliary pages, clear context menu coords. // Launched from some auxiliary pages, clear context menu coords.
µb.mouseX = µb.mouseY = -1; µb.mouseX = µb.mouseY = -1;
@ -155,6 +159,11 @@ var onMessage = function(request, sender, callback) {
µb.selectFilterLists(request.switches); µb.selectFilterLists(request.switches);
break; break;
case 'setWhitelist':
µb.netWhitelist = µb.whitelistFromString(request.whitelist);
µb.saveWhitelist();
break;
case 'toggleHostnameSwitch': case 'toggleHostnameSwitch':
µb.toggleHostnameSwitch(request); µb.toggleHostnameSwitch(request);
break; break;
@ -179,7 +188,7 @@ vAPI.messaging.setup(onMessage);
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/
// popup.js // channel: popupPanel
(function() { (function() {
@ -432,7 +441,7 @@ var onMessage = function(request, sender, callback) {
callback(response); callback(response);
}; };
vAPI.messaging.listen('popup.js', onMessage); vAPI.messaging.listen('popupPanel', onMessage);
/******************************************************************************/ /******************************************************************************/
@ -441,60 +450,7 @@ vAPI.messaging.listen('popup.js', onMessage);
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/
// contentscript-start.js // channel: contentscript
(function() {
'use strict';
/******************************************************************************/
var µb = µBlock;
/******************************************************************************/
var onMessage = function(request, sender, callback) {
// Async
switch ( request.what ) {
default:
break;
}
// Sync
var response;
var pageStore;
if ( sender && sender.tab ) {
pageStore = µb.pageStoreFromTabId(sender.tab.id);
}
switch ( request.what ) {
case 'retrieveDomainCosmeticSelectors':
if ( pageStore && pageStore.getNetFilteringSwitch() ) {
response = µb.cosmeticFilteringEngine.retrieveDomainSelectors(request);
if ( response && response.skipCosmeticFiltering !== true ) {
response.skipCosmeticFiltering = !pageStore.getSpecificCosmeticFilteringSwitch();
}
}
break;
default:
return vAPI.messaging.UNHANDLED;
}
callback(response);
};
vAPI.messaging.listen('contentscript-start.js', onMessage);
/******************************************************************************/
})();
/******************************************************************************/
/******************************************************************************/
// contentscript-end.js
(function() { (function() {
@ -575,6 +531,15 @@ var onMessage = function(request, sender, callback) {
} }
switch ( request.what ) { switch ( request.what ) {
case 'retrieveDomainCosmeticSelectors':
if ( pageStore && pageStore.getNetFilteringSwitch() ) {
response = µb.cosmeticFilteringEngine.retrieveDomainSelectors(request);
if ( response && response.skipCosmeticFiltering !== true ) {
response.skipCosmeticFiltering = !pageStore.getSpecificCosmeticFilteringSwitch();
}
}
break;
case 'retrieveGenericCosmeticSelectors': case 'retrieveGenericCosmeticSelectors':
response = { response = {
shutdown: !pageStore || !pageStore.getNetFilteringSwitch(), shutdown: !pageStore || !pageStore.getNetFilteringSwitch(),
@ -602,7 +567,7 @@ var onMessage = function(request, sender, callback) {
callback(response); callback(response);
}; };
vAPI.messaging.listen('contentscript-end.js', onMessage); vAPI.messaging.listen('contentscript', onMessage);
/******************************************************************************/ /******************************************************************************/
@ -611,7 +576,7 @@ vAPI.messaging.listen('contentscript-end.js', onMessage);
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/
// element-picker.js // channel: elementPicker
(function() { (function() {
@ -681,7 +646,7 @@ var onMessage = function(request, sender, callback) {
callback(response); callback(response);
}; };
vAPI.messaging.listen('element-picker.js', onMessage); vAPI.messaging.listen('elementPicker', onMessage);
/******************************************************************************/ /******************************************************************************/
@ -690,7 +655,7 @@ vAPI.messaging.listen('element-picker.js', onMessage);
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/
// cloud-ui.js // channel: cloudWidget
(function() { (function() {
@ -743,7 +708,7 @@ var onMessage = function(request, sender, callback) {
callback(response); callback(response);
}; };
vAPI.messaging.listen('cloud-ui.js', onMessage); vAPI.messaging.listen('cloudWidget', onMessage);
/******************************************************************************/ /******************************************************************************/
@ -752,7 +717,7 @@ vAPI.messaging.listen('cloud-ui.js', onMessage);
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/
// 3p-filters.js // channel: dashboard
(function() { (function() {
@ -764,309 +729,7 @@ var µb = µBlock;
/******************************************************************************/ /******************************************************************************/
var prepEntries = function(entries) { // Settings
var µburi = µb.URI;
var entry, hn;
for ( var k in entries ) {
if ( entries.hasOwnProperty(k) === false ) {
continue;
}
entry = entries[k];
if ( typeof entry.supportURL === 'string' && entry.supportURL !== '' ) {
entry.supportName = µburi.hostnameFromURI(entry.supportURL);
} else if ( typeof entry.homeURL === 'string' && entry.homeURL !== '' ) {
hn = µburi.hostnameFromURI(entry.homeURL);
entry.supportURL = 'http://' + hn + '/';
entry.supportName = µburi.domainFromHostname(hn);
}
}
};
/******************************************************************************/
var getLists = function(callback) {
var r = {
autoUpdate: µb.userSettings.autoUpdate,
available: null,
cache: null,
cosmetic: µb.userSettings.parseAllABPHideFilters,
cosmeticFilterCount: µb.cosmeticFilteringEngine.getFilterCount(),
current: µb.remoteBlacklists,
manualUpdate: false,
netFilterCount: µb.staticNetFilteringEngine.getFilterCount(),
userFiltersPath: µb.userFiltersPath
};
var onMetadataReady = function(entries) {
r.cache = entries;
r.manualUpdate = µb.assetUpdater.manualUpdate;
r.manualUpdateProgress = µb.assetUpdater.manualUpdateProgress;
prepEntries(r.cache);
callback(r);
};
var onLists = function(lists) {
r.available = lists;
prepEntries(r.available);
µb.assets.metadata(onMetadataReady);
};
µb.getAvailableLists(onLists);
};
/******************************************************************************/
var onMessage = function(request, sender, callback) {
// Async
switch ( request.what ) {
case 'getLists':
return getLists(callback);
case 'purgeAllCaches':
return µb.assets.purgeAll(callback);
default:
break;
}
// Sync
var response;
switch ( request.what ) {
case 'purgeCache':
µb.assets.purgeCacheableAsset(request.path);
break;
default:
return vAPI.messaging.UNHANDLED;
}
callback(response);
};
vAPI.messaging.listen('3p-filters.js', onMessage);
/******************************************************************************/
})();
/******************************************************************************/
/******************************************************************************/
// 1p-filters.js
(function() {
'use strict';
/******************************************************************************/
var µb = µBlock;
/******************************************************************************/
var onMessage = function(request, sender, callback) {
// Async
switch ( request.what ) {
case 'readUserFilters':
return µb.loadUserFilters(callback);
case 'writeUserFilters':
return µb.saveUserFilters(request.content, callback);
default:
break;
}
// Sync
var response;
switch ( request.what ) {
default:
return vAPI.messaging.UNHANDLED;
}
callback(response);
};
vAPI.messaging.listen('1p-filters.js', onMessage);
/******************************************************************************/
})();
/******************************************************************************/
/******************************************************************************/
// dyna-rules.js
(function() {
'use strict';
/******************************************************************************/
var µb = µBlock;
/******************************************************************************/
var getRules = function() {
return {
permanentRules: µb.permanentFirewall.toString() + '\n' + µb.permanentURLFiltering.toString(),
sessionRules: µb.sessionFirewall.toString() + '\n' + µb.sessionURLFiltering.toString(),
hnSwitches: µb.hnSwitches.toString()
};
};
// Untangle firewall rules, url rules and switches.
var untangle = function(s) {
var textEnd = s.length;
var lineBeg = 0, lineEnd;
var line;
var firewallRules = [];
var urlRules = [];
var switches = [];
while ( lineBeg < textEnd ) {
lineEnd = s.indexOf('\n', lineBeg);
if ( lineEnd < 0 ) {
lineEnd = s.indexOf('\r', lineBeg);
if ( lineEnd < 0 ) {
lineEnd = textEnd;
}
}
line = s.slice(lineBeg, lineEnd).trim();
lineBeg = lineEnd + 1;
if ( line.indexOf('://') !== -1 ) {
urlRules.push(line);
} else if ( line.indexOf(':') === -1 ) {
firewallRules.push(line);
} else {
switches.push(line);
}
}
return {
firewallRules: firewallRules.join('\n'),
urlRules: urlRules.join('\n'),
switches: switches.join('\n')
};
};
/******************************************************************************/
var onMessage = function(request, sender, callback) {
// Async
switch ( request.what ) {
default:
break;
}
// Sync
var r;
var response;
switch ( request.what ) {
case 'getRules':
response = getRules();
break;
case 'setSessionRules':
// https://github.com/chrisaljoudi/uBlock/issues/772
µb.cosmeticFilteringEngine.removeFromSelectorCache('*');
r = untangle(request.rules);
µb.sessionFirewall.fromString(r.firewallRules);
µb.sessionURLFiltering.fromString(r.urlRules);
µb.hnSwitches.fromString(r.switches);
µb.saveHostnameSwitches();
response = getRules();
break;
case 'setPermanentRules':
r = untangle(request.rules);
µb.permanentFirewall.fromString(r.firewallRules);
µb.savePermanentFirewallRules();
µb.permanentURLFiltering.fromString(r.urlRules);
µb.savePermanentURLFilteringRules();
µb.hnSwitches.fromString(r.switches);
µb.saveHostnameSwitches();
response = getRules();
break;
default:
return vAPI.messaging.UNHANDLED;
}
callback(response);
};
vAPI.messaging.listen('dyna-rules.js', onMessage);
/******************************************************************************/
})();
/******************************************************************************/
/******************************************************************************/
// whitelist.js
(function() {
'use strict';
/******************************************************************************/
var µb = µBlock;
/******************************************************************************/
var onMessage = function(request, sender, callback) {
// Async
switch ( request.what ) {
default:
break;
}
// Sync
var response;
switch ( request.what ) {
case 'getWhitelist':
response = µb.stringFromWhitelist(µb.netWhitelist);
break;
case 'setWhitelist':
µb.netWhitelist = µb.whitelistFromString(request.whitelist);
µb.saveWhitelist();
break;
default:
return vAPI.messaging.UNHANDLED;
}
callback(response);
};
vAPI.messaging.listen('whitelist.js', onMessage);
/******************************************************************************/
})();
/******************************************************************************/
/******************************************************************************/
// settings.js
(function() {
'use strict';
/******************************************************************************/
var µb = µBlock;
/******************************************************************************/
var getLocalData = function(callback) { var getLocalData = function(callback) {
var onStorageInfoReady = function(bytesInUse) { var onStorageInfoReady = function(bytesInUse) {
@ -1083,8 +746,6 @@ var getLocalData = function(callback) {
µb.getBytesInUse(onStorageInfoReady); µb.getBytesInUse(onStorageInfoReady);
}; };
/******************************************************************************/
var backupUserData = function(callback) { var backupUserData = function(callback) {
var userData = { var userData = {
timeStamp: Date.now(), timeStamp: Date.now(),
@ -1126,8 +787,6 @@ var backupUserData = function(callback) {
µb.assets.get(µb.userFiltersPath, onUserFiltersReady); µb.assets.get(µb.userFiltersPath, onUserFiltersReady);
}; };
/******************************************************************************/
var restoreUserData = function(request) { var restoreUserData = function(request) {
var userData = request.userData; var userData = request.userData;
var countdown = 8; var countdown = 8;
@ -1171,8 +830,6 @@ var restoreUserData = function(request) {
vAPI.storage.clear(onAllRemoved); vAPI.storage.clear(onAllRemoved);
}; };
/******************************************************************************/
var resetUserData = function() { var resetUserData = function() {
vAPI.storage.clear(); vAPI.storage.clear();
@ -1184,15 +841,124 @@ var resetUserData = function() {
/******************************************************************************/ /******************************************************************************/
// 3rd-party filters
var prepListEntries = function(entries) {
var µburi = µb.URI;
var entry, hn;
for ( var k in entries ) {
if ( entries.hasOwnProperty(k) === false ) {
continue;
}
entry = entries[k];
if ( typeof entry.supportURL === 'string' && entry.supportURL !== '' ) {
entry.supportName = µburi.hostnameFromURI(entry.supportURL);
} else if ( typeof entry.homeURL === 'string' && entry.homeURL !== '' ) {
hn = µburi.hostnameFromURI(entry.homeURL);
entry.supportURL = 'http://' + hn + '/';
entry.supportName = µburi.domainFromHostname(hn);
}
}
};
var getLists = function(callback) {
var r = {
autoUpdate: µb.userSettings.autoUpdate,
available: null,
cache: null,
cosmetic: µb.userSettings.parseAllABPHideFilters,
cosmeticFilterCount: µb.cosmeticFilteringEngine.getFilterCount(),
current: µb.remoteBlacklists,
manualUpdate: false,
netFilterCount: µb.staticNetFilteringEngine.getFilterCount(),
userFiltersPath: µb.userFiltersPath
};
var onMetadataReady = function(entries) {
r.cache = entries;
r.manualUpdate = µb.assetUpdater.manualUpdate;
r.manualUpdateProgress = µb.assetUpdater.manualUpdateProgress;
prepListEntries(r.cache);
callback(r);
};
var onLists = function(lists) {
r.available = lists;
prepListEntries(r.available);
µb.assets.metadata(onMetadataReady);
};
µb.getAvailableLists(onLists);
};
/******************************************************************************/
// My rules
var getRules = function() {
return {
permanentRules: µb.permanentFirewall.toString() + '\n' + µb.permanentURLFiltering.toString(),
sessionRules: µb.sessionFirewall.toString() + '\n' + µb.sessionURLFiltering.toString(),
hnSwitches: µb.hnSwitches.toString()
};
};
// Untangle firewall rules, url rules and switches.
var untangleRules = function(s) {
var textEnd = s.length;
var lineBeg = 0, lineEnd;
var line;
var firewallRules = [];
var urlRules = [];
var switches = [];
while ( lineBeg < textEnd ) {
lineEnd = s.indexOf('\n', lineBeg);
if ( lineEnd < 0 ) {
lineEnd = s.indexOf('\r', lineBeg);
if ( lineEnd < 0 ) {
lineEnd = textEnd;
}
}
line = s.slice(lineBeg, lineEnd).trim();
lineBeg = lineEnd + 1;
if ( line.indexOf('://') !== -1 ) {
urlRules.push(line);
} else if ( line.indexOf(':') === -1 ) {
firewallRules.push(line);
} else {
switches.push(line);
}
}
return {
firewallRules: firewallRules.join('\n'),
urlRules: urlRules.join('\n'),
switches: switches.join('\n')
};
};
/******************************************************************************/
var onMessage = function(request, sender, callback) { var onMessage = function(request, sender, callback) {
// Async // Async
switch ( request.what ) { switch ( request.what ) {
case 'backupUserData': case 'backupUserData':
return backupUserData(callback); return backupUserData(callback);
case 'getLists':
return getLists(callback);
case 'getLocalData': case 'getLocalData':
return getLocalData(callback); return getLocalData(callback);
case 'purgeAllCaches':
return µb.assets.purgeAll(callback);
case 'readUserFilters':
return µb.loadUserFilters(callback);
case 'writeUserFilters':
return µb.saveUserFilters(request.content, callback);
default: default:
break; break;
} }
@ -1201,6 +967,14 @@ var onMessage = function(request, sender, callback) {
var response; var response;
switch ( request.what ) { switch ( request.what ) {
case 'getRules':
response = getRules();
break;
case 'purgeCache':
µb.assets.purgeCacheableAsset(request.path);
break;
case 'restoreUserData': case 'restoreUserData':
restoreUserData(request); restoreUserData(request);
break; break;
@ -1209,6 +983,28 @@ var onMessage = function(request, sender, callback) {
resetUserData(); resetUserData();
break; break;
case 'setSessionRules':
// https://github.com/chrisaljoudi/uBlock/issues/772
µb.cosmeticFilteringEngine.removeFromSelectorCache('*');
response = untangleRules(request.rules);
µb.sessionFirewall.fromString(response.firewallRules);
µb.sessionURLFiltering.fromString(response.urlRules);
µb.hnSwitches.fromString(response.switches);
µb.saveHostnameSwitches();
response = getRules();
break;
case 'setPermanentRules':
response = untangleRules(request.rules);
µb.permanentFirewall.fromString(response.firewallRules);
µb.savePermanentFirewallRules();
µb.permanentURLFiltering.fromString(response.urlRules);
µb.savePermanentURLFilteringRules();
µb.hnSwitches.fromString(response.switches);
µb.saveHostnameSwitches();
response = getRules();
break;
default: default:
return vAPI.messaging.UNHANDLED; return vAPI.messaging.UNHANDLED;
} }
@ -1216,7 +1012,7 @@ var onMessage = function(request, sender, callback) {
callback(response); callback(response);
}; };
vAPI.messaging.listen('settings.js', onMessage); vAPI.messaging.listen('dashboard', onMessage);
/******************************************************************************/ /******************************************************************************/
@ -1225,7 +1021,7 @@ vAPI.messaging.listen('settings.js', onMessage);
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/
// logger-ui.js // channel: loggerUI
(function() { (function() {
@ -1329,7 +1125,7 @@ var onMessage = function(request, sender, callback) {
callback(response); callback(response);
}; };
vAPI.messaging.listen('logger-ui.js', onMessage); vAPI.messaging.listen('loggerUI', onMessage);
/******************************************************************************/ /******************************************************************************/
@ -1340,7 +1136,7 @@ vAPI.messaging.listen('logger-ui.js', onMessage);
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/
// document-blocked.js // channel: documentBlocked
(function() { (function() {
@ -1370,7 +1166,7 @@ var onMessage = function(request, sender, callback) {
callback(response); callback(response);
}; };
vAPI.messaging.listen('document-blocked.js', onMessage); vAPI.messaging.listen('documentBlocked', onMessage);
/******************************************************************************/ /******************************************************************************/
@ -1379,7 +1175,7 @@ vAPI.messaging.listen('document-blocked.js', onMessage);
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/
// scriptlets // channel: scriptlets
(function() { (function() {

View File

@ -1,7 +1,7 @@
/******************************************************************************* /*******************************************************************************
µBlock - a browser extension to block requests. uBlock Origin - a browser extension to block requests.
Copyright (C) 2014 Raymond Hill Copyright (C) 2014-2016 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/uBlock Home: https://github.com/gorhill/uBlock
*/ */
/* global punycode, vAPI, uDom */ /* global punycode, uDom */
/******************************************************************************/ /******************************************************************************/
@ -81,6 +81,7 @@ if ( dfPaneVisibleStored ) {
/******************************************************************************/ /******************************************************************************/
var messaging = vAPI.messaging;
var popupData = {}; var popupData = {};
var dfPaneBuilt = false; var dfPaneBuilt = false;
var reIP = /^\d+(?:\.\d+){1,3}$/; var reIP = /^\d+(?:\.\d+){1,3}$/;
@ -106,12 +107,6 @@ var reNetworkRelatedURL = /^(?:ftps?|https?|wss?):\/\//;
/******************************************************************************/ /******************************************************************************/
// https://github.com/gorhill/httpswitchboard/issues/345
var messager = vAPI.messaging.channel('popup.js');
/******************************************************************************/
var cachePopupData = function(data) { var cachePopupData = function(data) {
popupData = {}; popupData = {};
scopeToSrcHostnameMap['.'] = ''; scopeToSrcHostnameMap['.'] = '';
@ -519,10 +514,14 @@ var renderPopupLazy = function() {
.textContent = typeof v === 'number' ? v.toLocaleString() : v; .textContent = typeof v === 'number' ? v.toLocaleString() : v;
}; };
messager.send({ messaging.send(
what: 'getPopupDataLazy', 'popupPanel',
tabId: popupData.tabId {
}, onDataReady); what: 'getPopupDataLazy',
tabId: popupData.tabId
},
onDataReady
);
}; };
/******************************************************************************/ /******************************************************************************/
@ -534,13 +533,16 @@ var toggleNetFilteringSwitch = function(ev) {
if ( popupData.pageHostname === 'behind-the-scene' && !popupData.advancedUserEnabled ) { if ( popupData.pageHostname === 'behind-the-scene' && !popupData.advancedUserEnabled ) {
return; return;
} }
messager.send({ messaging.send(
what: 'toggleNetFiltering', 'popupPanel',
url: popupData.pageURL, {
scope: ev.ctrlKey || ev.metaKey ? 'page' : '', what: 'toggleNetFiltering',
state: !uDom('body').toggleClass('off').hasClass('off'), url: popupData.pageURL,
tabId: popupData.tabId scope: ev.ctrlKey || ev.metaKey ? 'page' : '',
}); state: !uDom('body').toggleClass('off').hasClass('off'),
tabId: popupData.tabId
}
);
hashFromPopupData(); hashFromPopupData();
}; };
@ -548,10 +550,13 @@ var toggleNetFilteringSwitch = function(ev) {
/******************************************************************************/ /******************************************************************************/
var gotoPick = function() { var gotoPick = function() {
messager.send({ messaging.send(
what: 'launchElementPicker', 'popupPanel',
tabId: popupData.tabId {
}); what: 'launchElementPicker',
tabId: popupData.tabId
}
);
vAPI.closePopup(); vAPI.closePopup();
}; };
@ -567,15 +572,18 @@ var gotoURL = function(ev) {
var rel = this.getAttribute('rel') || ''; var rel = this.getAttribute('rel') || '';
messager.send({ messaging.send(
what: 'gotoURL', 'popupPanel',
details: { {
url: this.getAttribute('href'), what: 'gotoURL',
select: true, details: {
index: -1, url: this.getAttribute('href'),
popup: rel === 'popup' && ev.shiftKey select: true,
index: -1,
popup: rel === 'popup' && ev.shiftKey
}
} }
}); );
vAPI.closePopup(); vAPI.closePopup();
}; };
@ -588,11 +596,14 @@ var toggleFirewallPane = function() {
} }
popupData.dfEnabled = !popupData.dfEnabled; popupData.dfEnabled = !popupData.dfEnabled;
messager.send({ messaging.send(
what: 'userSettings', 'popupPanel',
name: 'dynamicFilteringEnabled', {
value: popupData.dfEnabled what: 'userSettings',
}); name: 'dynamicFilteringEnabled',
value: popupData.dfEnabled
}
);
// https://github.com/chrisaljoudi/uBlock/issues/996 // https://github.com/chrisaljoudi/uBlock/issues/996
// Remember the last state of the firewall pane. This allows to // Remember the last state of the firewall pane. This allows to
@ -632,16 +643,20 @@ var setFirewallRule = function(src, des, type, action, persist) {
updateAllFirewallCells(); updateAllFirewallCells();
hashFromPopupData(); hashFromPopupData();
}; };
messager.send({ messaging.send(
what: 'toggleFirewallRule', 'popupPanel',
tabId: popupData.tabId, {
pageHostname: popupData.pageHostname, what: 'toggleFirewallRule',
srcHostname: src, tabId: popupData.tabId,
desHostname: des, pageHostname: popupData.pageHostname,
requestType: type, srcHostname: src,
action: action, desHostname: des,
persist: persist requestType: type,
}, onFirewallRuleChanged); action: action,
persist: persist
},
onFirewallRuleChanged
);
}; };
/******************************************************************************/ /******************************************************************************/
@ -688,7 +703,14 @@ var setFirewallRuleHandler = function(ev) {
/******************************************************************************/ /******************************************************************************/
var reloadTab = function() { var reloadTab = function() {
messager.send({ what: 'reloadTab', tabId: popupData.tabId, select: true }); messaging.send(
'popupPanel',
{
what: 'reloadTab',
tabId: popupData.tabId,
select: true
}
);
// Polling will take care of refreshing the popup content // Polling will take care of refreshing the popup content
@ -708,14 +730,17 @@ var toggleMinimize = function(ev) {
// Useful to take snapshots of the whole list of domains -- example: // Useful to take snapshots of the whole list of domains -- example:
// https://github.com/gorhill/uBlock/issues/736#issuecomment-178879944 // https://github.com/gorhill/uBlock/issues/736#issuecomment-178879944
if ( ev.shiftKey && ev.ctrlKey ) { if ( ev.shiftKey && ev.ctrlKey ) {
messager.send({ messaging.send(
what: 'gotoURL', 'popupPanel',
details: { {
url: 'popup.html?tabId=' + popupData.tabId + '&fullsize=1', what: 'gotoURL',
select: true, details: {
index: -1 url: 'popup.html?tabId=' + popupData.tabId + '&fullsize=1',
select: true,
index: -1
}
} }
}); );
vAPI.closePopup(); vAPI.closePopup();
return; return;
} }
@ -723,22 +748,28 @@ var toggleMinimize = function(ev) {
popupData.firewallPaneMinimized = uDom.nodeFromId('firewallContainer') popupData.firewallPaneMinimized = uDom.nodeFromId('firewallContainer')
.classList .classList
.toggle('minimized'); .toggle('minimized');
messager.send({ messaging.send(
what: 'userSettings', 'popupPanel',
name: 'firewallPaneMinimized', {
value: popupData.firewallPaneMinimized what: 'userSettings',
}); name: 'firewallPaneMinimized',
value: popupData.firewallPaneMinimized
}
);
positionRulesetTools(); positionRulesetTools();
}; };
/******************************************************************************/ /******************************************************************************/
var saveFirewallRules = function() { var saveFirewallRules = function() {
messager.send({ messaging.send(
what: 'saveFirewallRules', 'popupPanel',
srcHostname: popupData.pageHostname, {
desHostnames: popupData.hostnameDict what: 'saveFirewallRules',
}); srcHostname: popupData.pageHostname,
desHostnames: popupData.hostnameDict
}
);
uDom.nodeFromId('firewallContainer').classList.remove('dirty'); uDom.nodeFromId('firewallContainer').classList.remove('dirty');
}; };
@ -750,12 +781,16 @@ var revertFirewallRules = function() {
updateAllFirewallCells(); updateAllFirewallCells();
hashFromPopupData(); hashFromPopupData();
}; };
messager.send({ messaging.send(
what: 'revertFirewallRules', 'popupPanel',
srcHostname: popupData.pageHostname, {
desHostnames: popupData.hostnameDict, what: 'revertFirewallRules',
tabId: popupData.tabId srcHostname: popupData.pageHostname,
}, onFirewallRuleChanged); desHostnames: popupData.hostnameDict,
tabId: popupData.tabId
},
onFirewallRuleChanged
);
uDom.nodeFromId('firewallContainer').classList.remove('dirty'); uDom.nodeFromId('firewallContainer').classList.remove('dirty');
}; };
@ -768,13 +803,16 @@ var toggleHostnameSwitch = function(ev) {
return; return;
} }
target.classList.toggle('on'); target.classList.toggle('on');
messager.send({ messaging.send(
what: 'toggleHostnameSwitch', 'popupPanel',
name: switchName, {
hostname: popupData.pageHostname, what: 'toggleHostnameSwitch',
state: target.classList.contains('on'), name: switchName,
tabId: popupData.tabId hostname: popupData.pageHostname,
}); state: target.classList.contains('on'),
tabId: popupData.tabId
}
);
hashFromPopupData(); hashFromPopupData();
}; };
@ -803,7 +841,8 @@ var pollForContentChange = (function() {
var pollCallback = function() { var pollCallback = function() {
pollTimer = null; pollTimer = null;
messager.send( messaging.send(
'popupPanel',
{ {
what: 'hasPopupContentChanged', what: 'hasPopupContentChanged',
tabId: popupData.tabId, tabId: popupData.tabId,
@ -841,7 +880,11 @@ var getPopupData = function(tabId) {
hashFromPopupData(true); hashFromPopupData(true);
pollForContentChange(); pollForContentChange();
}; };
messager.send({ what: 'getPopupData', tabId: tabId }, onDataReceived); messaging.send(
'popupPanel',
{ what: 'getPopupData', tabId: tabId },
onDataReceived
);
}; };
/******************************************************************************/ /******************************************************************************/

View File

@ -1,7 +1,7 @@
/******************************************************************************* /*******************************************************************************
uBlock - a browser extension to block requests. uBlock Origin - a browser extension to block requests.
Copyright (C) 2015 Raymond Hill Copyright (C) 2015-2016 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
@ -71,17 +71,15 @@ vAPI.loggedSelectors = loggedSelectors;
/******************************************************************************/ /******************************************************************************/
var localMessager = vAPI.messaging.channel('scriptlets'); vAPI.messaging.send(
'scriptlets',
localMessager.send({ {
what: 'logCosmeticFilteringData', what: 'logCosmeticFilteringData',
frameURL: window.location.href, frameURL: window.location.href,
frameHostname: window.location.hostname, frameHostname: window.location.hostname,
matchedSelectors: matchedSelectors matchedSelectors: matchedSelectors
}, function() { }
localMessager.close(); );
localMessager = null;
});
/******************************************************************************/ /******************************************************************************/

View File

@ -1,7 +1,7 @@
/******************************************************************************* /*******************************************************************************
uBlock - a browser extension to block requests. uBlock Origin - a browser extension to block requests.
Copyright (C) 2015 Raymond Hill Copyright (C) 2015-2016 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
@ -53,15 +53,14 @@ if ( injectedSelectors.length !== 0 ) {
/******************************************************************************/ /******************************************************************************/
var localMessager = vAPI.messaging.channel('scriptlets'); vAPI.messaging.send(
'scriptlets',
localMessager.send({ {
what: 'liveCosmeticFilteringData', what: 'liveCosmeticFilteringData',
pageURL: window.location.href, pageURL: window.location.href,
filteredElementCount: filteredElementCount filteredElementCount: filteredElementCount
}, function() { }
localMessager.close(); );
});
/******************************************************************************/ /******************************************************************************/

View File

@ -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-2016 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
@ -137,8 +137,6 @@ var cssEscape = (function(/*root*/) {
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/
var localMessager = vAPI.messaging.channel('dom-inspector.js');
// Highlighter-related // Highlighter-related
var svgRoot = null; var svgRoot = null;
var pickerRoot = null; var pickerRoot = null;
@ -903,9 +901,7 @@ var shutdown = function() {
cosmeticFilterMapper.shutdown(); cosmeticFilterMapper.shutdown();
resetToggledNodes(); resetToggledNodes();
domLayout.shutdown(); domLayout.shutdown();
localMessager.removeAllListeners(); vAPI.messaging.removeAllChannelListeners('domInspector');
localMessager.close();
localMessager = null;
window.removeEventListener('scroll', onScrolled, true); window.removeEventListener('scroll', onScrolled, true);
document.documentElement.removeChild(pickerRoot); document.documentElement.removeChild(pickerRoot);
pickerRoot = svgRoot = null; pickerRoot = svgRoot = null;
@ -1150,7 +1146,7 @@ pickerRoot.onload = function() {
highlightElements(); highlightElements();
cosmeticFilterMapper.reset(); cosmeticFilterMapper.reset();
localMessager.addListener(onMessage); vAPI.messaging.addChannelListener('domInspector', onMessage);
}; };
document.documentElement.appendChild(pickerRoot); document.documentElement.appendChild(pickerRoot);

View File

@ -1,7 +1,7 @@
/******************************************************************************* /*******************************************************************************
µBlock - a browser extension to block requests. uBlock Origin - a browser extension to block requests.
Copyright (C) 2014 Raymond Hill Copyright (C) 2014-2016 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
@ -135,8 +135,6 @@ if ( pickerRoot ) {
return; return;
} }
var localMessager = vAPI.messaging.channel('element-picker.js');
var svgOcean = null; var svgOcean = null;
var svgIslands = null; var svgIslands = null;
var svgRoot = null; var svgRoot = null;
@ -292,12 +290,15 @@ var netFilterFromUnion = (function() {
if ( from === '' || a.host === '' || a.host !== lastNetFilterHostname ) { if ( from === '' || a.host === '' || a.host !== lastNetFilterHostname ) {
lastNetFilterHostname = a.host; lastNetFilterHostname = a.host;
lastNetFilterUnion = to; lastNetFilterUnion = to;
localMessager.send({ vAPI.messaging.send(
what: 'elementPickerEprom', 'elementPicker',
lastNetFilterSession: lastNetFilterSession, {
lastNetFilterHostname: lastNetFilterHostname, what: 'elementPickerEprom',
lastNetFilterUnion: lastNetFilterUnion lastNetFilterSession: lastNetFilterSession,
}); lastNetFilterHostname: lastNetFilterHostname,
lastNetFilterUnion: lastNetFilterUnion
}
);
return; return;
} }
@ -338,12 +339,15 @@ var netFilterFromUnion = (function() {
lastNetFilterUnion = from; lastNetFilterUnion = from;
// Remember across element picker sessions // Remember across element picker sessions
localMessager.send({ vAPI.messaging.send(
what: 'elementPickerEprom', 'elementPicker',
lastNetFilterSession: lastNetFilterSession, {
lastNetFilterHostname: lastNetFilterHostname, what: 'elementPickerEprom',
lastNetFilterUnion: lastNetFilterUnion lastNetFilterSession: lastNetFilterSession,
}); lastNetFilterHostname: lastNetFilterHostname,
lastNetFilterUnion: lastNetFilterUnion
}
);
}; };
})(); })();
@ -694,10 +698,13 @@ var onDialogClicked = function(ev) {
var filter = userFilterFromCandidate(); var filter = userFilterFromCandidate();
if ( filter ) { if ( filter ) {
var d = new Date(); var d = new Date();
localMessager.send({ vAPI.messaging.send(
what: 'createUserFilter', 'elementPicker',
filters: '! ' + d.toLocaleString() + ' ' + window.location.href + '\n' + filter, {
}); what: 'createUserFilter',
filters: '! ' + d.toLocaleString() + ' ' + window.location.href + '\n' + filter,
}
);
removeElements(elementsFromFilter(taCandidate.value)); removeElements(elementsFromFilter(taCandidate.value));
stopPicker(); stopPicker();
} }
@ -901,7 +908,6 @@ var stopPicker = function() {
dialog = dialog =
svgRoot = svgOcean = svgIslands = svgRoot = svgOcean = svgIslands =
taCandidate = null; taCandidate = null;
localMessager.close();
window.focus(); window.focus();
}; };
@ -1037,7 +1043,12 @@ pickerRoot.style.cssText = [
].join('!important; '); ].join('!important; ');
pickerRoot.onload = function() { pickerRoot.onload = function() {
localMessager.send({ what: 'elementPickerArguments' }, startPicker); vAPI.shutdown.add(stopPicker);
vAPI.messaging.send(
'elementPicker',
{ what: 'elementPickerArguments' },
startPicker
);
}; };
document.documentElement.appendChild(pickerRoot); document.documentElement.appendChild(pickerRoot);

View File

@ -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-2016 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
@ -114,10 +114,6 @@ document.head.appendChild(styleTag);
/******************************************************************************/ /******************************************************************************/
var messager = vAPI.messaging.channel('scriptlets');
/******************************************************************************/
var stayOrLeave = (function() { var stayOrLeave = (function() {
var timer = null; var timer = null;
@ -139,10 +135,6 @@ var stayOrLeave = (function() {
vAPI.loadLargeMediaInteractive = false; vAPI.loadLargeMediaInteractive = false;
document.removeEventListener('error', onLoadError, true); document.removeEventListener('error', onLoadError, true);
document.removeEventListener('click', onMouseClick, true); document.removeEventListener('click', onMouseClick, true);
if ( messager !== null ) {
messager.close();
messager = null;
}
}; };
return function(leaveNow) { return function(leaveNow) {
@ -184,9 +176,11 @@ var onMouseClick = function(ev) {
stayOrLeave(); stayOrLeave();
}; };
messager.send({ vAPI.messaging.send(
what: 'temporarilyAllowLargeMediaElement' 'scriptlets',
}, onLargeMediaElementAllowed); { what: 'temporarilyAllowLargeMediaElement' },
onLargeMediaElementAllowed
);
ev.preventDefault(); ev.preventDefault();
ev.stopPropagation(); ev.stopPropagation();

View File

@ -1,7 +1,7 @@
/******************************************************************************* /*******************************************************************************
µBlock - a browser extension to block requests. uBlock Origin - a browser extension to block requests.
Copyright (C) 2015 Raymond Hill Copyright (C) 2015-2016 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
@ -59,10 +59,6 @@ if (
/******************************************************************************/ /******************************************************************************/
var messager = vAPI.messaging.channel('scriptlets');
/******************************************************************************/
var onAbpLinkClicked = function(ev) { var onAbpLinkClicked = function(ev) {
if ( ev.button !== 0 ) { if ( ev.button !== 0 ) {
return; return;
@ -87,21 +83,27 @@ var onAbpLinkClicked = function(ev) {
return; return;
} }
} }
var location = decodeURIComponent(matches[1]); var location = decodeURIComponent(matches[1]);
var title = decodeURIComponent(matches[2]); var title = decodeURIComponent(matches[2]);
var messaging = vAPI.messaging;
ev.stopPropagation(); ev.stopPropagation();
ev.preventDefault(); ev.preventDefault();
var onListsSelectionDone = function() { var onListsSelectionDone = function() {
messager.send({ what: 'reloadAllFilters' }); messaging.send('scriptlets', { what: 'reloadAllFilters' });
}; };
var onExternalListsSaved = function() { var onExternalListsSaved = function() {
messager.send({ messaging.send(
what: 'selectFilterLists', 'scriptlets',
switches: [ { location: location, off: false } ] {
}, onListsSelectionDone); what: 'selectFilterLists',
switches: [ { location: location, off: false } ]
},
onListsSelectionDone
);
}; };
var onSubscriberDataReady = function(details) { var onSubscriberDataReady = function(details) {
@ -122,14 +124,22 @@ var onAbpLinkClicked = function(ev) {
} }
lines.push(location, ''); lines.push(location, '');
messager.send({ messaging.send(
what: 'userSettings', 'scriptlets',
name: 'externalLists', {
value: lines.join('\n') what: 'userSettings',
}, onExternalListsSaved); name: 'externalLists',
value: lines.join('\n')
},
onExternalListsSaved
);
}; };
messager.send({ what: 'subscriberData' }, onSubscriberDataReady); messaging.send(
'scriptlets',
{ what: 'subscriberData' },
onSubscriberDataReady
);
}; };
document.addEventListener('click', onAbpLinkClicked, true); document.addEventListener('click', onAbpLinkClicked, true);

View File

@ -1,7 +1,7 @@
/******************************************************************************* /*******************************************************************************
µBlock - a browser extension to block requests. uBlock Origin - a browser extension to block requests.
Copyright (C) 2014 Raymond Hill Copyright (C) 2014-2016 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/uBlock Home: https://github.com/gorhill/uBlock
*/ */
/* global vAPI, uDom */ /* global uDom */
/******************************************************************************/ /******************************************************************************/
@ -29,7 +29,7 @@
/******************************************************************************/ /******************************************************************************/
var messager = vAPI.messaging.channel('settings.js'); var messaging = vAPI.messaging;
/******************************************************************************/ /******************************************************************************/
@ -72,11 +72,14 @@ var handleImportFilePicker = function() {
.replace('{{time}}', time.toLocaleString()); .replace('{{time}}', time.toLocaleString());
var proceed = window.confirm(msg); var proceed = window.confirm(msg);
if ( proceed ) { if ( proceed ) {
messager.send({ messaging.send(
what: 'restoreUserData', 'dashboard',
userData: userData, {
file: filename what: 'restoreUserData',
}); userData: userData,
file: filename
}
);
} }
}; };
@ -99,7 +102,7 @@ var startImportFilePicker = function() {
/******************************************************************************/ /******************************************************************************/
var exportToFile = function() { var exportToFile = function() {
messager.send({ what: 'backupUserData' }, onLocalDataReceived); messaging.send('dashboard', { what: 'backupUserData' }, onLocalDataReceived);
}; };
/******************************************************************************/ /******************************************************************************/
@ -143,18 +146,21 @@ var resetUserData = function() {
var msg = vAPI.i18n('aboutResetDataConfirm'); var msg = vAPI.i18n('aboutResetDataConfirm');
var proceed = window.confirm(msg); var proceed = window.confirm(msg);
if ( proceed ) { if ( proceed ) {
messager.send({ what: 'resetUserData' }); messaging.send('dashboard', { what: 'resetUserData' });
} }
}; };
/******************************************************************************/ /******************************************************************************/
var changeUserSettings = function(name, value) { var changeUserSettings = function(name, value) {
messager.send({ messaging.send(
what: 'userSettings', 'dashboard',
name: name, {
value: value what: 'userSettings',
}); name: name,
value: value
}
);
}; };
/******************************************************************************/ /******************************************************************************/
@ -216,8 +222,8 @@ var onUserSettingsReceived = function(details) {
/******************************************************************************/ /******************************************************************************/
uDom.onLoad(function() { uDom.onLoad(function() {
messager.send({ what: 'userSettings' }, onUserSettingsReceived); messaging.send('dashboard', { what: 'userSettings' }, onUserSettingsReceived);
messager.send({ what: 'getLocalData' }, onLocalDataReceived); messaging.send('dashboard', { what: 'getLocalData' }, onLocalDataReceived);
}); });
/******************************************************************************/ /******************************************************************************/

View File

@ -1,7 +1,7 @@
/******************************************************************************* /*******************************************************************************
µBlock - a browser extension to block requests. uBlock Origin - a browser extension to block requests.
Copyright (C) 2014 Raymond Hill Copyright (C) 2014-2016 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/uBlock Home: https://github.com/gorhill/uBlock
*/ */
/* global vAPI, uDom, uBlockDashboard */ /* global uDom, uBlockDashboard */
/******************************************************************************/ /******************************************************************************/
@ -29,10 +29,7 @@
/******************************************************************************/ /******************************************************************************/
var messager = vAPI.messaging.channel('whitelist.js'); var messaging = vAPI.messaging;
/******************************************************************************/
var cachedWhitelist = ''; var cachedWhitelist = '';
// Could make it more fancy if needed. But speed... It's a compromise. // Could make it more fancy if needed. But speed... It's a compromise.
@ -58,7 +55,7 @@ var renderWhitelist = function() {
uDom.nodeFromId('whitelist').value = cachedWhitelist + '\n'; uDom.nodeFromId('whitelist').value = cachedWhitelist + '\n';
whitelistChanged(); whitelistChanged();
}; };
messager.send({ what: 'getWhitelist' }, onRead); messaging.send('dashboard', { what: 'getWhitelist' }, onRead);
}; };
/******************************************************************************/ /******************************************************************************/
@ -117,7 +114,7 @@ var applyChanges = function() {
what: 'setWhitelist', what: 'setWhitelist',
whitelist: cachedWhitelist whitelist: cachedWhitelist
}; };
messager.send(request, renderWhitelist); messaging.send('dashboard', request, renderWhitelist);
}; };
var revertChanges = function() { var revertChanges = function() {