1
0
Fork 0
mirror of https://github.com/gorhill/uMatrix.git synced 2024-05-18 11:13:28 +12:00
uMatrix/src/js/contentscript.js

549 lines
19 KiB
JavaScript
Raw Normal View History

2014-10-18 08:01:09 +13:00
/*******************************************************************************
uMatrix - a browser extension to black/white list requests.
Copyright (C) 2014-present Raymond Hill
2014-10-18 08:01:09 +13:00
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/uMatrix
*/
2017-12-11 11:09:35 +13:00
/* global HTMLDocument, XMLDocument */
2014-10-18 08:01:09 +13:00
'use strict';
2014-10-18 08:01:09 +13:00
/******************************************************************************/
/******************************************************************************/
2015-04-12 09:15:57 +12:00
// Injected into content pages
2014-10-18 08:01:09 +13:00
(( ) => {
2014-10-18 08:01:09 +13:00
2015-04-12 09:15:57 +12:00
/******************************************************************************/
2014-10-18 08:01:09 +13:00
2015-04-12 09:15:57 +12:00
// https://github.com/chrisaljoudi/uBlock/issues/464
2017-12-11 11:09:35 +13:00
// https://github.com/gorhill/uMatrix/issues/621
if (
document instanceof HTMLDocument === false &&
document instanceof XMLDocument === false
) {
return;
}
// This can also happen (for example if script injected into a `data:` URI doc)
if ( !window.location ) { return; }
2014-10-18 08:01:09 +13:00
2015-04-12 09:15:57 +12:00
// This can happen
2015-05-18 07:00:37 +12:00
if ( typeof vAPI !== 'object' ) {
//console.debug('contentscript.js > vAPI not found');
2015-04-12 09:15:57 +12:00
return;
}
2014-10-18 08:01:09 +13:00
2015-04-12 09:15:57 +12:00
// https://github.com/chrisaljoudi/uBlock/issues/456
// Already injected?
if ( vAPI.contentscriptEndInjected ) {
//console.debug('contentscript.js > content script already injected');
2015-04-12 09:15:57 +12:00
return;
}
vAPI.contentscriptEndInjected = true;
2014-10-18 08:01:09 +13:00
/******************************************************************************/
/******************************************************************************/
// Executed only once.
2014-10-18 08:01:09 +13:00
{
const localStorageHandler = function(mustRemove) {
if ( mustRemove ) {
window.localStorage.clear();
window.sessionStorage.clear();
}
};
// Check with extension whether local storage must be emptied
// rhill 2014-03-28: we need an exception handler in case 3rd-party access
// to site data is disabled.
// https://github.com/gorhill/httpswitchboard/issues/215
try {
const hasLocalStorage =
2017-12-10 04:45:37 +13:00
window.localStorage && window.localStorage.length !== 0;
const hasSessionStorage =
2017-12-10 04:45:37 +13:00
window.sessionStorage && window.sessionStorage.length !== 0;
if ( hasLocalStorage || hasSessionStorage ) {
vAPI.messaging.send('contentscript.js', {
what: 'contentScriptHasLocalStorage',
originURL: window.location.origin,
}).then(response => {
localStorageHandler(response);
});
}
// TODO: indexedDB
//if ( window.indexedDB && !!window.indexedDB.webkitGetDatabaseNames ) {
// var db = window.indexedDB.webkitGetDatabaseNames().onsuccess = function(sender) {
// console.debug('webkitGetDatabaseNames(): result=%o', sender.target.result);
// };
//}
// TODO: Web SQL
2017-12-12 02:31:09 +13:00
// if ( window.openDatabase ) {
// Sad:
// "There is no way to enumerate or delete the databases available for an origin from this API."
// Ref.: http://www.w3.org/TR/webdatabase/#databases
2017-12-12 02:31:09 +13:00
// }
2014-10-18 08:01:09 +13:00
}
catch (e) {
2014-10-18 08:01:09 +13:00
}
}
2014-10-18 08:01:09 +13:00
/******************************************************************************/
2014-10-18 08:01:09 +13:00
/******************************************************************************/
// https://github.com/gorhill/uMatrix/issues/45
const collapser = (( ) => {
let resquestIdGenerator = 1,
processTimer,
toProcess = [],
toFilter = [],
cachedBlockedMap,
cachedBlockedMapHash,
cachedBlockedMapTimer;
const toCollapse = new Map();
const reURLPlaceholder = /\{\{url\}\}/g;
const src1stProps = {
'embed': 'src',
'frame': 'src',
'iframe': 'src',
'img': 'src',
'object': 'data'
};
const src2ndProps = {
'img': 'srcset'
};
const tagToTypeMap = {
embed: 'media',
frame: 'frame',
iframe: 'frame',
img: 'image',
object: 'media'
};
const cachedBlockedSetClear = function() {
cachedBlockedMap =
cachedBlockedMapHash =
cachedBlockedMapTimer = undefined;
};
// https://github.com/chrisaljoudi/uBlock/issues/174
// Do not remove fragment from src URL
const onProcessed = function(response) {
if ( !response ) { // This happens if uBO is disabled or restarted.
toCollapse.clear();
return;
}
const targets = toCollapse.get(response.id);
if ( targets === undefined ) { return; }
toCollapse.delete(response.id);
if ( cachedBlockedMapHash !== response.hash ) {
cachedBlockedMap = new Map(response.blockedResources);
cachedBlockedMapHash = response.hash;
if ( cachedBlockedMapTimer !== undefined ) {
clearTimeout(cachedBlockedMapTimer);
}
cachedBlockedMapTimer = vAPI.setTimeout(cachedBlockedSetClear, 30000);
}
if ( cachedBlockedMap === undefined || cachedBlockedMap.size === 0 ) {
return;
}
2015-05-04 00:18:06 +12:00
const placeholders = response.placeholders;
for ( const target of targets ) {
const tag = target.localName;
let prop = src1stProps[tag];
if ( prop === undefined ) { continue; }
let src = target[prop];
if ( typeof src !== 'string' || src.length === 0 ) {
prop = src2ndProps[tag];
if ( prop === undefined ) { continue; }
src = target[prop];
if ( typeof src !== 'string' || src.length === 0 ) { continue; }
}
const collapsed = cachedBlockedMap.get(tagToTypeMap[tag] + ' ' + src);
if ( collapsed === undefined ) { continue; }
if ( collapsed ) {
target.style.setProperty('display', 'none', 'important');
target.hidden = true;
2015-05-03 23:33:24 +12:00
continue;
2015-05-03 04:07:40 +12:00
}
2018-01-07 12:00:28 +13:00
switch ( tag ) {
case 'frame':
2018-01-07 12:00:28 +13:00
case 'iframe':
if ( placeholders.frame !== true ) { break; }
const docurl =
'data:text/html,' +
encodeURIComponent(
2018-01-07 12:00:28 +13:00
placeholders.frameDocument.replace(
reURLPlaceholder,
src
)
);
let replaced = false;
// Using contentWindow.location prevent tainting browser
// history -- i.e. breaking back button (seen on Chromium).
if ( target.contentWindow ) {
2016-11-16 04:05:05 +13:00
try {
target.contentWindow.location.replace(docurl);
replaced = true;
} catch(ex) {
}
}
if ( !replaced ) {
target.setAttribute('src', docurl);
}
2018-01-07 12:00:28 +13:00
break;
case 'img':
if ( placeholders.image !== true ) { break; }
// Do not insert placeholder if the image was actually loaded.
// This can happen if an allow rule was created while the
// document was loading.
if (
target.complete &&
target.naturalWidth !== 0 &&
target.naturalHeight !== 0
) {
break;
}
2018-01-07 12:00:28 +13:00
target.style.setProperty('display', 'inline-block');
target.style.setProperty('min-width', '20px', 'important');
target.style.setProperty('min-height', '20px', 'important');
target.style.setProperty(
'border',
placeholders.imageBorder,
'important'
);
target.style.setProperty(
'background',
placeholders.imageBackground,
'important'
);
break;
2015-05-03 23:58:10 +12:00
}
}
};
const send = function() {
processTimer = undefined;
toCollapse.set(resquestIdGenerator, toProcess);
vAPI.messaging.send('contentscript.js', {
what: 'lookupBlockedCollapsibles',
id: resquestIdGenerator,
toFilter: toFilter,
hash: cachedBlockedMapHash,
}).then(response => {
onProcessed(response);
});
toProcess = [];
toFilter = [];
resquestIdGenerator += 1;
};
2014-10-18 08:01:09 +13:00
const process = function(delay) {
if ( toProcess.length === 0 ) { return; }
if ( delay === 0 ) {
if ( processTimer !== undefined ) {
clearTimeout(processTimer);
}
send();
} else if ( processTimer === undefined ) {
processTimer = vAPI.setTimeout(send, delay || 47);
}
};
const add = function(target) {
toProcess.push(target);
};
var addMany = function(targets) {
var i = targets.length;
while ( i-- ) {
toProcess.push(targets[i]);
}
};
2014-10-18 08:01:09 +13:00
const iframeSourceModified = function(mutations) {
let i = mutations.length;
2015-05-03 23:10:05 +12:00
while ( i-- ) {
addIFrame(mutations[i].target, true);
2015-05-03 23:10:05 +12:00
}
process();
};
let iframeSourceObserver;
const iframeSourceObserverOptions = {
2015-05-03 23:10:05 +12:00
attributes: true,
attributeFilter: [ 'src' ],
2015-05-03 23:10:05 +12:00
};
const addIFrame = function(iframe, dontObserve) {
2015-05-03 23:10:05 +12:00
// https://github.com/gorhill/uBlock/issues/162
// Be prepared to deal with possible change of src attribute.
if ( dontObserve !== true ) {
if ( iframeSourceObserver === undefined ) {
2015-05-04 01:06:35 +12:00
iframeSourceObserver = new MutationObserver(iframeSourceModified);
}
2015-05-03 23:10:05 +12:00
iframeSourceObserver.observe(iframe, iframeSourceObserverOptions);
}
const src = iframe.src;
if ( src === '' || typeof src !== 'string' ) { return; }
if ( src.startsWith('http') === false ) { return; }
toFilter.push({ type: 'frame', url: iframe.src });
add(iframe);
};
2014-10-18 08:01:09 +13:00
const addIFrames = function(iframes) {
let i = iframes.length;
while ( i-- ) {
addIFrame(iframes[i]);
}
};
2014-10-18 08:01:09 +13:00
const addNodeList = function(nodeList) {
let i = nodeList.length;
while ( i-- ) {
const node = nodeList[i];
if ( node.nodeType !== 1 ) { continue; }
if ( node.localName === 'iframe' || node.localName === 'frame' ) {
addIFrame(node);
}
if ( node.childElementCount !== 0 ) {
addIFrames(node.querySelectorAll('iframe, frame'));
}
}
};
2014-10-18 08:01:09 +13:00
const onResourceFailed = function(ev) {
if ( tagToTypeMap[ev.target.localName] !== undefined ) {
add(ev.target);
process();
}
};
document.addEventListener('error', onResourceFailed, true);
vAPI.shutdown.add(function() {
document.removeEventListener('error', onResourceFailed, true);
if ( iframeSourceObserver !== undefined ) {
2015-05-04 01:06:35 +12:00
iframeSourceObserver.disconnect();
iframeSourceObserver = undefined;
}
if ( processTimer !== undefined ) {
clearTimeout(processTimer);
processTimer = undefined;
2015-05-04 01:06:35 +12:00
}
});
return {
addMany,
addIFrames,
addNodeList,
process,
};
})();
2014-10-18 08:01:09 +13:00
/******************************************************************************/
2014-10-18 08:01:09 +13:00
/******************************************************************************/
// Observe changes in the DOM
// Added node lists will be cumulated here before being processed
(( ) => {
// This fixes http://acid3.acidtests.org/
if ( !document.body ) { return; }
let addedNodeLists = [];
let addedNodeListsTimer;
const treeMutationObservedHandler = function() {
2017-12-12 02:31:09 +13:00
addedNodeListsTimer = undefined;
let i = addedNodeLists.length;
2017-12-12 02:31:09 +13:00
while ( i-- ) {
collapser.addNodeList(addedNodeLists[i]);
}
collapser.process();
addedNodeLists = [];
};
// https://github.com/gorhill/uBlock/issues/205
// Do not handle added node directly from within mutation observer.
const treeMutationObservedHandlerAsync = function(mutations) {
let iMutation = mutations.length;
while ( iMutation-- ) {
const nodeList = mutations[iMutation].addedNodes;
if ( nodeList.length !== 0 ) {
addedNodeLists.push(nodeList);
}
2014-10-18 08:01:09 +13:00
}
2017-12-12 02:31:09 +13:00
if ( addedNodeListsTimer === undefined ) {
addedNodeListsTimer = vAPI.setTimeout(treeMutationObservedHandler, 47);
}
};
2014-10-18 08:01:09 +13:00
// https://github.com/gorhill/httpswitchboard/issues/176
let treeObserver = new MutationObserver(treeMutationObservedHandlerAsync);
treeObserver.observe(document.body, {
2014-10-18 08:01:09 +13:00
childList: true,
subtree: true
});
vAPI.shutdown.add(function() {
2017-12-12 02:31:09 +13:00
if ( addedNodeListsTimer !== undefined ) {
clearTimeout(addedNodeListsTimer);
2017-12-12 02:31:09 +13:00
addedNodeListsTimer = undefined;
}
if ( treeObserver !== null ) {
treeObserver.disconnect();
2017-12-12 02:31:09 +13:00
treeObserver = undefined;
}
addedNodeLists = [];
});
})();
2014-10-18 08:01:09 +13:00
/******************************************************************************/
2014-10-18 08:01:09 +13:00
/******************************************************************************/
// Executed only once.
2018-01-23 07:58:35 +13:00
//
2017-12-12 02:31:09 +13:00
// https://github.com/gorhill/httpswitchboard/issues/25
2018-01-23 07:58:35 +13:00
//
2017-12-12 02:31:09 +13:00
// https://github.com/gorhill/httpswitchboard/issues/131
// Looks for inline javascript also in at least one a[href] element.
2018-01-23 07:58:35 +13:00
//
2017-12-12 02:31:09 +13:00
// https://github.com/gorhill/uMatrix/issues/485
// Mind "on..." attributes.
2018-01-23 07:58:35 +13:00
//
// https://github.com/gorhill/uMatrix/issues/924
// Report inline styles.
2017-12-12 02:31:09 +13:00
{
if (
document.querySelector('script:not([src])') !== null ||
document.querySelector('a[href^="javascript:"]') !== null ||
document.querySelector('[onabort],[onblur],[oncancel],[oncanplay],[oncanplaythrough],[onchange],[onclick],[onclose],[oncontextmenu],[oncuechange],[ondblclick],[ondrag],[ondragend],[ondragenter],[ondragexit],[ondragleave],[ondragover],[ondragstart],[ondrop],[ondurationchange],[onemptied],[onended],[onerror],[onfocus],[oninput],[oninvalid],[onkeydown],[onkeypress],[onkeyup],[onload],[onloadeddata],[onloadedmetadata],[onloadstart],[onmousedown],[onmouseenter],[onmouseleave],[onmousemove],[onmouseout],[onmouseover],[onmouseup],[onwheel],[onpause],[onplay],[onplaying],[onprogress],[onratechange],[onreset],[onresize],[onscroll],[onseeked],[onseeking],[onselect],[onshow],[onstalled],[onsubmit],[onsuspend],[ontimeupdate],[ontoggle],[onvolumechange],[onwaiting],[onafterprint],[onbeforeprint],[onbeforeunload],[onhashchange],[onlanguagechange],[onmessage],[onoffline],[ononline],[onpagehide],[onpageshow],[onrejectionhandled],[onpopstate],[onstorage],[onunhandledrejection],[onunload],[oncopy],[oncut],[onpaste]') !== null
) {
vAPI.messaging.send('contentscript.js', {
what: 'securityPolicyViolation',
directive: 'script-src',
documentURI: window.location.href,
});
}
2017-12-12 02:31:09 +13:00
2018-01-23 07:58:35 +13:00
if ( document.querySelector('style,[style]') !== null ) {
vAPI.messaging.send('contentscript.js', {
what: 'securityPolicyViolation',
directive: 'style-src',
documentURI: window.location.href,
2018-01-23 07:58:35 +13:00
});
}
2017-12-12 02:31:09 +13:00
collapser.addMany(document.querySelectorAll('img'));
collapser.addIFrames(document.querySelectorAll('iframe, frame'));
2017-12-12 02:31:09 +13:00
collapser.process();
}
2017-12-12 02:31:09 +13:00
/******************************************************************************/
/******************************************************************************/
// Executed only once.
2017-12-02 06:34:29 +13:00
// https://github.com/gorhill/uMatrix/issues/232
// Force `display` property, Firefox is still affected by the issue.
(( ) => {
const noscripts = document.querySelectorAll('noscript');
if ( noscripts.length === 0 ) { return; }
const reMetaContent = /^\s*(\d+)\s*;\s*url=(['"]?)([^'"]+)\2/i;
const reSafeURL = /^https?:\/\//;
let redirectTimer;
const autoRefresh = function(root) {
const meta = root.querySelector('meta[http-equiv="refresh"][content]');
if ( meta === null ) { return; }
const match = reMetaContent.exec(meta.getAttribute('content'));
if ( match === null || match[3].trim() === '' ) { return; }
const url = new URL(match[3], document.baseURI);
2017-12-09 02:21:26 +13:00
if ( reSafeURL.test(url.href) === false ) { return; }
redirectTimer = setTimeout(
( ) => {
2017-12-09 02:21:26 +13:00
location.assign(url.href);
},
parseInt(match[1], 10) * 1000 + 1
);
meta.parentNode.removeChild(meta);
};
const morphNoscript = function(from) {
if ( /^application\/(?:xhtml\+)?xml/.test(document.contentType) ) {
const to = document.createElement('span');
while ( from.firstChild !== null ) {
to.appendChild(from.firstChild);
}
return to;
}
const parser = new DOMParser();
const doc = parser.parseFromString(
'<span>' + from.textContent + '</span>',
'text/html'
);
return document.adoptNode(doc.querySelector('span'));
};
const renderNoscriptTags = function(response) {
if ( response !== true ) { return; }
for ( var noscript of noscripts ) {
const parent = noscript.parentNode;
if ( parent === null ) { continue; }
const span = morphNoscript(noscript);
2017-12-02 06:34:29 +13:00
span.style.setProperty('display', 'inline', 'important');
if ( redirectTimer === undefined ) {
autoRefresh(span);
}
parent.replaceChild(span, noscript);
}
};
vAPI.messaging.send('contentscript.js', {
what: 'mustRenderNoscriptTags?',
}).then(response => {
renderNoscriptTags(response);
});
})();
/******************************************************************************/
/******************************************************************************/
vAPI.messaging.send('contentscript.js', {
what: 'shutdown?',
}).then(response => {
if ( response === true ) {
vAPI.shutdown.exec();
}
});
2015-04-12 09:15:57 +12:00
/******************************************************************************/
/******************************************************************************/
})();