uBlock/js/contentscript-end.js

526 lines
17 KiB
JavaScript
Raw Normal View History

2014-06-24 00:42:43 +02:00
/*******************************************************************************
µBlock - a Chromium browser extension to block requests.
Copyright (C) 2014 Raymond Hill
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
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see {http://www.gnu.org/licenses/}.
Home: https://github.com/gorhill/uBlock
*/
/* global chrome */
// Injected into content pages
/******************************************************************************/
/******************************************************************************/
// https://github.com/gorhill/httpswitchboard/issues/345
var uBlockMessaging = (function(name){
2014-06-24 00:42:43 +02:00
var port = null;
var dangling = false;
var requestId = 1;
var requestIdToCallbackMap = {};
var listenCallback = null;
var onPortMessage = function(details) {
if ( typeof details.id !== 'number' ) {
return;
}
// Announcement?
if ( details.id < 0 ) {
if ( listenCallback ) {
listenCallback(details.msg);
}
return;
}
var callback = requestIdToCallbackMap[details.id];
if ( !callback ) {
return;
}
callback(details.msg);
delete requestIdToCallbackMap[details.id];
checkDisconnect();
};
var start = function(name) {
port = chrome.runtime.connect({
name: name +
'/' +
String.fromCharCode(
Math.random() * 0x7FFF | 0,
Math.random() * 0x7FFF | 0,
Math.random() * 0x7FFF | 0,
Math.random() * 0x7FFF | 0
)
});
port.onMessage.addListener(onPortMessage);
};
if ( typeof name === 'string' && name.length > 0 ) {
start(name);
}
var stop = function() {
listenCallback = null;
dangling = true;
checkDisconnect();
};
var ask = function(msg, callback) {
if ( !callback ) {
tell(msg);
return;
}
var id = requestId++;
port.postMessage({ id: id, msg: msg });
requestIdToCallbackMap[id] = callback;
};
var tell = function(msg) {
port.postMessage({ id: 0, msg: msg });
};
var listen = function(callback) {
listenCallback = callback;
};
var checkDisconnect = function() {
if ( !dangling ) {
return;
}
if ( Object.keys(requestIdToCallbackMap).length ) {
return;
}
port.disconnect();
port = null;
};
return {
start: start,
stop: stop,
ask: ask,
tell: tell,
listen: listen
};
})('contentscript-end.js');
/******************************************************************************/
/******************************************************************************/
// ABP cosmetic filters
(function() {
var messaging = uBlockMessaging;
2014-07-02 18:02:29 +02:00
var queriedSelectors = {};
var injectedSelectors = {};
var classSelectors = null;
var idSelectors = null;
var highGenerics = null;
var contextNodes = [document];
2014-07-02 18:02:29 +02:00
var domLoaded = function() {
// https://github.com/gorhill/uBlock/issues/14
// Treat any existing domain-specific exception selectors as if they had
// been injected already.
var style = document.getElementById('uBlock1ae7a5f130fc79b4fdb8a4272d9426b5');
var exceptions = style && style.getAttribute('uBlock1ae7a5f130fc79b4fdb8a4272d9426b5');
if ( exceptions ) {
2014-08-07 22:12:15 +02:00
exceptions = JSON.parse(exceptions);
2014-07-02 18:02:29 +02:00
var i = exceptions.length;
while ( i-- ) {
injectedSelectors[exceptions[i]] = true;
}
2014-06-26 00:44:35 +02:00
}
2014-07-20 21:00:26 +02:00
idsFromNodeList(document.querySelectorAll('[id]'));
classesFromNodeList(document.querySelectorAll('[class]'));
2014-07-02 18:02:29 +02:00
retrieveGenericSelectors();
};
2014-06-24 00:42:43 +02:00
2014-07-02 18:02:29 +02:00
var retrieveGenericSelectors = function() {
var selectors = classSelectors !== null ? Object.keys(classSelectors) : [];
if ( idSelectors !== null ) {
selectors = selectors.concat(idSelectors);
2014-06-24 00:42:43 +02:00
}
if ( selectors.length > 0 || highGenerics === null ) {
2014-07-02 18:02:29 +02:00
//console.log('µBlock> ABP cosmetic filters: retrieving CSS rules using %d selectors', selectors.length);
messaging.ask({
what: 'retrieveGenericCosmeticSelectors',
pageURL: window.location.href,
selectors: selectors,
highGenerics: highGenerics === null
2014-07-02 18:02:29 +02:00
},
retrieveHandler
);
} else {
retrieveHandler(null);
2014-07-02 18:02:29 +02:00
}
idSelectors = null;
classSelectors = null;
};
2014-06-24 00:42:43 +02:00
2014-07-02 18:02:29 +02:00
var retrieveHandler = function(selectors) {
//console.debug('µBlock> contextNodes = %o', contextNodes);
if ( selectors && selectors.highGenerics ) {
highGenerics = selectors.highGenerics;
2014-06-24 00:42:43 +02:00
}
if ( selectors && selectors.donthide.length ) {
processLowGenerics(selectors.donthide);
}
if ( highGenerics ) {
if ( highGenerics.donthideLowCount ) {
processHighLowGenerics(highGenerics.donthideLow);
}
if ( highGenerics.donthideMediumCount ) {
processHighMediumGenerics(highGenerics.donthideMedium);
2014-08-07 22:12:15 +02:00
}
}
// No such thing as high-high generic exceptions
//if ( highGenerics.donthideHighCount ) {
// processHighHighGenerics(document, highGenerics.donthideHigh);
//}
var hideSelectors = [];
if ( selectors && selectors.hide.length ) {
processLowGenerics(selectors.hide, hideSelectors);
}
if ( highGenerics ) {
if ( highGenerics.hideLowCount ) {
processHighLowGenerics(highGenerics.hideLow, hideSelectors);
}
if ( highGenerics.hideMediumCount ) {
processHighMediumGenerics(highGenerics.hideMedium, hideSelectors);
}
if ( highGenerics.hideHighCount ) {
processHighHighGenerics(highGenerics.hideHigh, hideSelectors);
}
}
if ( hideSelectors.length ) {
applyCSS(hideSelectors, 'display', 'none');
2014-07-02 18:02:29 +02:00
var style = document.createElement('style');
var text = hideSelectors.join(',\n') + ' {display:none !important;}';
2014-08-07 22:12:15 +02:00
style.appendChild(document.createTextNode(text));
2014-07-02 18:02:29 +02:00
var parent = document.body || document.documentElement;
if ( parent ) {
parent.appendChild(style);
2014-06-24 00:42:43 +02:00
}
//console.debug('µBlock> generic cosmetic filters: injecting %d CSS rules:', hideSelectors.length, text);
2014-06-24 00:42:43 +02:00
}
contextNodes.length = 0;
2014-07-02 18:02:29 +02:00
};
2014-06-24 00:42:43 +02:00
2014-07-02 18:02:29 +02:00
var applyCSS = function(selectors, prop, value) {
if ( document.body === null ) {
return;
2014-06-24 00:42:43 +02:00
}
2014-07-02 18:02:29 +02:00
var elems = document.querySelectorAll(selectors);
var i = elems.length;
while ( i-- ) {
elems[i].style[prop] = value;
2014-06-24 00:42:43 +02:00
}
2014-07-02 18:02:29 +02:00
};
var selectNodes = function(selector) {
var targetNodes = [];
var i = contextNodes.length;
var node, nodeList, j;
var doc = document;
while ( i-- ) {
node = contextNodes[i];
if ( node === doc ) {
return doc.querySelectorAll(selector);
}
targetNodes.push(node);
nodeList = node.querySelectorAll(selector);
j = nodeList.length;
while ( j-- ) {
targetNodes.push(nodeList[j]);
}
2014-07-04 22:47:34 +02:00
}
return targetNodes;
2014-07-04 22:47:34 +02:00
};
var processLowGenerics = function(generics, out) {
var i = generics.length;
var selector;
while ( i-- ) {
selector = generics[i];
if ( injectedSelectors[selector] !== undefined ) {
continue;
}
injectedSelectors[selector] = true;
if ( out !== undefined ) {
out.push(selector);
}
2014-07-04 22:47:34 +02:00
}
};
var processHighLowGenerics = function(generics, out) {
var attrs = ['title', 'alt'];
var attr, attrValue, nodeList, iNode, node, selector;
while ( attr = attrs.pop() ) {
nodeList = selectNodes('[' + attr + ']');
iNode = nodeList.length;
while ( iNode-- ) {
node = nodeList[iNode];
attrValue = node.getAttribute(attr);
if ( !attrValue ) { continue; }
selector = '[' + attr + '="' + attrValue + '"]';
if ( injectedSelectors[selector] === undefined && generics[selector] ) {
injectedSelectors[selector] = true;
if ( out !== undefined ) {
out.push(selector);
}
}
selector = node.tagName.toLowerCase() + selector;
if ( injectedSelectors[selector] === undefined && generics[selector] ) {
injectedSelectors[selector] = true;
if ( out !== undefined ) {
out.push(selector);
}
}
}
2014-07-04 22:47:34 +02:00
}
};
var processHighMediumGenerics = function(generics, out) {
var nodeList = selectNodes('a[href^="http"]');
var iNode = nodeList.length;
var node, href, pos, hash, selector;
while ( iNode-- ) {
node = nodeList[iNode];
href = node.getAttribute('href');
if ( !href ) { continue; }
pos = href.indexOf('://');
if ( pos === -1 ) { continue; }
hash = href.slice(pos + 3, pos + 11);
selector = generics[hash];
if ( selector === undefined ) { continue; }
if ( injectedSelectors[selector] !== undefined ) { continue; }
injectedSelectors[selector] = true;
if ( out !== undefined ) {
2014-07-04 22:47:34 +02:00
out.push(selector);
2014-07-02 18:02:29 +02:00
}
}
};
var processHighHighGenerics = function(generics, out) {
if ( injectedSelectors[generics] !== undefined ) { return; }
if ( document.querySelectorAll(generics) === null ) { return; }
injectedSelectors[generics] = true;
if ( out !== undefined ) {
var selectors = generics.split(',\n');
var i = selectors.length;
while ( i-- ) {
if ( injectedSelectors[selectors[i]] !== undefined ) {
selectors.splice(i, 1);
2014-07-02 18:02:29 +02:00
}
}
out.push(selectors.join(',\n'));
2014-07-02 18:02:29 +02:00
}
};
2014-07-20 21:00:26 +02:00
var idsFromNodeList = function(nodes) {
2014-07-02 18:02:29 +02:00
if ( !nodes || !nodes.length ) {
return;
2014-06-24 00:42:43 +02:00
}
2014-07-02 18:02:29 +02:00
if ( idSelectors === null ) {
idSelectors = [];
}
var qq = queriedSelectors;
var ii = idSelectors;
2014-07-20 21:00:26 +02:00
var node, v;
2014-07-02 18:02:29 +02:00
var i = nodes.length;
while ( i-- ) {
node = nodes[i];
2014-07-20 21:00:26 +02:00
if ( node.nodeType !== 1 ) { continue; }
2014-07-02 18:02:29 +02:00
// id
2014-07-09 07:53:49 +02:00
v = nodes[i].id;
// quite unlikely, so no need to be fancy
2014-07-20 21:00:26 +02:00
if ( typeof v !== 'string' ) { continue; }
2014-07-09 07:53:49 +02:00
v = v.trim();
2014-07-20 21:00:26 +02:00
if ( v === '' ) { continue; }
v = '#' + v;
if ( qq[v] ) { continue; }
ii.push(v);
qq[v] = true;
}
};
var classesFromNodeList = function(nodes) {
if ( !nodes || !nodes.length ) {
return;
}
if ( classSelectors === null ) {
classSelectors = {};
}
var qq = queriedSelectors;
var cc = classSelectors;
var node, v, vv, j;
var i = nodes.length;
while ( i-- ) {
node = nodes[i];
if ( node.nodeType !== 1 ) { continue; }
2014-07-02 18:02:29 +02:00
// class
v = nodes[i].className;
// it could be an SVGAnimatedString...
if ( typeof v !== 'string' ) { continue; }
v = v.trim();
if ( v === '' ) { continue; }
// one class
if ( v.indexOf(' ') < 0 ) {
v = '.' + v;
if ( qq[v] ) { continue; }
cc[v] = true;
qq[v] = true;
2014-06-24 00:42:43 +02:00
continue;
}
2014-07-02 18:02:29 +02:00
// many classes
2014-07-20 21:00:26 +02:00
vv = v.trim().split(' ');
j = vv.length;
2014-07-02 18:02:29 +02:00
while ( j-- ) {
2014-07-20 21:00:26 +02:00
v = vv[j].trim();
2014-07-02 18:02:29 +02:00
if ( v === '' ) { continue; }
v = '.' + v;
if ( qq[v] ) { continue; }
cc[v] = true;
qq[v] = true;
}
2014-06-24 00:42:43 +02:00
}
2014-07-02 18:02:29 +02:00
};
2014-06-24 00:42:43 +02:00
2014-07-02 18:02:29 +02:00
domLoaded();
2014-06-24 00:42:43 +02:00
// Observe changes in the DOM only if...
// - there is a document.body
// - there is at least one `script` tag
if ( !document.body || !document.querySelector('script') ) {
return;
}
var ignoreTags = {
'style': true,
'STYLE': true,
'script': true,
'SCRIPT': true
};
var mutationObservedHandler = function(mutations) {
var iMutation = mutations.length;
var nodes = [];
var nodeList, iNode, node;
while ( iMutation-- ) {
nodeList = mutations[iMutation].addedNodes;
if ( !nodeList ) {
continue;
}
iNode = nodeList.length;
while ( iNode-- ) {
node = nodeList[iNode];
if ( typeof node.querySelectorAll !== 'function' ) {
continue;
}
if ( ignoreTags[node.tagName] ) {
continue;
}
contextNodes.push(node);
}
}
if ( contextNodes.length !== 0 ) {
idsFromNodeList(selectNodes('[id]'));
classesFromNodeList(selectNodes('[class]'));
retrieveGenericSelectors();
}
2014-07-02 18:02:29 +02:00
};
// https://github.com/gorhill/httpswitchboard/issues/176
var observer = new MutationObserver(mutationObservedHandler);
observer.observe(document.body, {
attributes: false,
childList: true,
characterData: false,
subtree: true
});
2014-07-02 18:02:29 +02:00
})();
2014-06-24 00:42:43 +02:00
2014-08-02 17:40:27 +02:00
/******************************************************************************/
2014-06-24 00:42:43 +02:00
/******************************************************************************/
2014-06-27 23:06:42 +02:00
// https://github.com/gorhill/uBlock/issues/7
2014-07-20 21:00:26 +02:00
(function() {
var messaging = uBlockMessaging;
2014-07-02 18:02:29 +02:00
var hideOne = function(elem, collapse) {
// If `!important` is not there, going back using history will likely
// cause the hidden element to re-appear.
elem.style.visibility = 'hidden !important';
if ( collapse && elem.parentNode ) {
elem.parentNode.removeChild(elem);
}
2014-06-29 18:38:18 +02:00
};
2014-07-20 21:00:26 +02:00
// First pass
messaging.ask({ what: 'blockedRequests' }, function(details) {
var elems = document.querySelectorAll('img,iframe,embed');
2014-07-02 18:02:29 +02:00
var blockedRequests = details.blockedRequests;
var collapse = details.collapse;
var i = elems.length;
var elem, src;
while ( i-- ) {
elem = elems[i];
src = elem.src;
2014-07-20 21:00:26 +02:00
if ( typeof src !== 'string' || src === '' ) {
2014-07-02 18:02:29 +02:00
continue;
}
2014-07-20 21:00:26 +02:00
if ( blockedRequests[src] ) {
2014-07-02 18:02:29 +02:00
hideOne(elem, collapse);
}
2014-06-27 23:06:42 +02:00
}
2014-07-20 21:00:26 +02:00
});
2014-07-02 18:02:29 +02:00
2014-07-20 21:00:26 +02:00
// Listeners to mop up whatever is otherwise missed:
// - Future requests not blocked yet
// - Elements dynamically added to the page
// - Elements which resource URL changes
var onResourceLoaded = function(ev) {
var target = ev.target;
//console.debug('Loaded %s[src="%s"]', target.tagName, target.src);
2014-08-06 17:34:59 +02:00
if ( !target || !target.src ) { return; }
if ( target.tagName.toLowerCase() !== 'iframe' ) { return; }
2014-08-02 17:40:27 +02:00
var onAnswerReceived = function(details) {
if ( details.blocked ) {
hideOne(target, details.collapse);
}
};
messaging.ask({ what: 'blockedRequest', url: target.src }, onAnswerReceived);
};
var onResourceFailed = function(ev) {
var target = ev.target;
//console.debug('Failed to load %s[src="%s"]', target.tagName, target.src);
2014-08-06 17:34:59 +02:00
if ( !target || !target.src ) { return; }
if ( target.tagName.toLowerCase() !== 'img' ) { return; }
2014-07-20 21:00:26 +02:00
var onAnswerReceived = function(details) {
if ( details.blocked ) {
hideOne(target, details.collapse);
}
};
messaging.ask({ what: 'blockedRequest', url: target.src }, onAnswerReceived);
2014-06-27 23:06:42 +02:00
};
2014-07-20 21:00:26 +02:00
document.addEventListener('load', onResourceLoaded, true);
2014-08-02 17:40:27 +02:00
document.addEventListener('error', onResourceFailed, true);
2014-07-02 18:02:29 +02:00
})();
2014-06-24 00:42:43 +02:00
/******************************************************************************/