remove google tracking UWAA

remove google tracking

当前为 2017-07-13 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @namespace jp.sceneq.rgtuwaaa
  3.  
  4. // @name remove google tracking UWAA
  5.  
  6. // @description remove google tracking
  7. // @description:ja Google追跡UWAAを取り除きなさい
  8.  
  9. // @homepageURL https://github.com/sceneq/RemoveGoogleTracking
  10.  
  11. // @version 0.6
  12. // @include https://www.google.*/*
  13. // @grant none
  14. // @run-at document-start
  15.  
  16. // @author sceneq
  17. // @license MIT
  18. // ==/UserScript==
  19.  
  20. 'use strict';
  21.  
  22. const yesman = function() {
  23. return true;
  24. };
  25. const tired = function() {};
  26.  
  27. // matching tracking paramaters
  28. const badParametersNames = [
  29. 'biw',
  30. 'bih',
  31. 'ei',
  32. 'sa',
  33. 'ved',
  34. 'source',
  35. 'prmd',
  36. 'bvm',
  37. 'bav',
  38. 'psi',
  39. 'stick',
  40. 'dq',
  41. 'ech',
  42.  
  43. // image search
  44. 'scroll',
  45. 'vet',
  46. 'yv',
  47. 'ijn',
  48. 'iact',
  49. 'forward',
  50. 'ndsp',
  51. 'csi',
  52. 'tbnid',
  53. 'docid',
  54. //'imgdii', // related images
  55.  
  56. // search form
  57. 'pbx',
  58. 'dpr',
  59. 'pf',
  60. 'gs_rn',
  61. 'gs_mss',
  62. 'pq',
  63. 'cp',
  64. 'oq',
  65. 'sclient',
  66. 'gs_l',
  67. 'aqs',
  68. //'gs_ri', // suggestions
  69. //'gs_id', // suggestions
  70. //'xhr', // suggestions at image search
  71. //'tch', // js flag?
  72.  
  73. // mobile
  74. 'gs_gbg',
  75. 'gs_rn',
  76. 'cp'
  77. ];
  78. const badAttrNamesObj = {
  79. default: ['onmousedown', 'ping', 'oncontextmenu'],
  80. search: ['onmousedown', 'ping', 'oncontextmenu'],
  81. vid: ['onmousedown'],
  82. isch: []
  83. };
  84.  
  85. // From the nodes selected here, delete parameters specified by badParametersNames
  86. const dirtyLinkSelectors = [
  87. // menu
  88. 'a.q.qs',
  89.  
  90. // doodle
  91. 'a.doodle'
  92. ];
  93.  
  94. const badPaths = ['imgevent'];
  95.  
  96. /* Compile */
  97. // The first paramater is probably 'q' so '?' does not consider
  98. const regBadParameters = new RegExp(
  99. '&(?:' + badParametersNames.join('|') + ')=.*?(?=(&|$))',
  100. 'g'
  101. );
  102. const regBadPaths = new RegExp('^/(?:' + badPaths.join('|') + ')');
  103. const dirtyLinkSelector = dirtyLinkSelectors
  104. .map(s => s + ":not([href=''])")
  105. .join(',');
  106.  
  107. /*
  108. * Functions
  109. */
  110. /* Return parameter value */
  111. function extractDirectLink(str, param) {
  112. //(?<=q=)(.*)(?=&)/
  113. const res = new RegExp(`[?&]${param}(=([^&#]*))`).exec(str);
  114. if (!res || !res[2]) return '';
  115. return decodeURIComponent(res[2]);
  116. }
  117.  
  118. /* Return the current Google search mode */
  119. function getParam(parameter, name) {
  120. var results = new RegExp('[?&]' + name + '=([^&#]*)').exec(parameter);
  121. if (results === null) {
  122. return null;
  123. } else {
  124. return results.pop() || 0;
  125. }
  126. }
  127.  
  128. /* return search mode */
  129. function getMode() {
  130. const parameter = location.search + location.hash;
  131. return getParam(parameter, 'tbm') || 'search';
  132. }
  133.  
  134. function sleep(ms) {
  135. return new Promise(resolve => setTimeout(resolve, ms));
  136. }
  137.  
  138. /* Return Promise when declared the variable name specified by argument */
  139. async function onDeclare(obj, propertyStr, interval = 80) {
  140. return new Promise(async function(resolve, reject) {
  141. const propertyNames = propertyStr.split('.');
  142. let currObj = obj;
  143. for (const propertyName of propertyNames) {
  144. while (!(propertyName in currObj) || currObj[propertyName] === null) {
  145. await sleep(interval);
  146. }
  147. currObj = currObj[propertyName];
  148. }
  149. resolve(currObj);
  150. });
  151. }
  152.  
  153. function removeDOM(node) {
  154. node.parentNode.removeChild(node);
  155. }
  156.  
  157. function rewriteProperties(prop) {
  158. prop.forEach(table => {
  159. //const targetObject = typeof table[0] === 'function' ? table[0]() : table[0];
  160. Object.defineProperty(table[0] || {}, table[1], {
  161. value: table[2],
  162. writable: false
  163. });
  164. });
  165. }
  166.  
  167. function load() {
  168. console.time('LOAD');
  169.  
  170. /* Overwrite disturbing functions */
  171. rewriteProperties([[window, 'rwt', yesman], [window.gbar_, 'Rm', yesman]]);
  172.  
  173. /*
  174. * Variables
  175. */
  176. // Whether to use AJAX
  177. const legacy = document.getElementById('cst') === null;
  178.  
  179. /* Nodes */
  180. const nodeMain = document.getElementById("main");
  181. const nodeCnt = document.getElementById("cnt");
  182. const root = (() => {
  183. if (legacy) {
  184. return nodeCnt || nodeMain || window.document;
  185. } else {
  186. return nodeMain; // || nodeCnt;
  187. }
  188. })();
  189.  
  190. // Flag indicating whether the hard tab is loaded on 'DOMContentLoaded'
  191. const lazy_hdtb = !legacy || root === nodeCnt;
  192.  
  193. // Define selector function
  194. const $ = root.querySelector.bind(root);
  195. const $$ = sel =>
  196. Array.prototype.slice.call(root.querySelectorAll.call(root, [sel]));
  197.  
  198. // Selector pointing to anchors to purify
  199. const dirtySelector = (() => {
  200. if (root === window.document) {
  201. return 'body a';
  202. } else if (legacy) {
  203. return `#${root.id} a`;
  204. } else {
  205. return '#rcnt a';
  206. }
  207. })();
  208.  
  209. /*
  210. * Functions
  211. */
  212. function removeTracking() {
  213. console.time('removeTracking');
  214. const mode = getMode();
  215. const badAttrNames = badAttrNamesObj[mode]
  216. ? badAttrNamesObj[mode]
  217. : badAttrNamesObj['default'];
  218. const directLinkParamName = 'q';
  219.  
  220. // search result
  221. for (const searchResult of $$(dirtySelector)) {
  222. // remove attributes
  223. badAttrNames.map(s => {
  224. searchResult.removeAttribute(s);
  225. });
  226.  
  227. // hide referrer
  228. searchResult.rel = 'noreferrer';
  229.  
  230. // remove google redirect link(legacy)
  231. if (
  232. searchResult.hasAttribute('href') &&
  233. searchResult.getAttribute('href').startsWith('/url?')
  234. ) {
  235. searchResult.href = extractDirectLink(
  236. searchResult.href,
  237. directLinkParamName
  238. );
  239. }
  240. searchResult.href = searchResult.href.replace(regBadParameters, '');
  241. }
  242. for (const dirtyLink of document.querySelectorAll(dirtyLinkSelector)) {
  243. dirtyLink.href = dirtyLink.href.replace(regBadParameters, '');
  244. }
  245.  
  246. switch (mode) {
  247. case 'shop':
  248. // Overwrite links(desktop version only)
  249. //Object.values(google.pmc.smpo.r).map(s=>{return {title:s[14][0],link:s[28][8]}})
  250. if (legacy) break;
  251. onDeclare(google, 'pmc.spop.r').then(shopObj => {
  252. const shopElements = $$('.pstl');
  253. const shopLinks = Object.values(shopObj).map(a => a[34][6]);
  254.  
  255. if (shopElements.length !== shopLinks.length) {
  256. console.warn(
  257. 'length does not match',
  258. shopElements.length,
  259. shopLinks.length
  260. );
  261. return;
  262. }
  263.  
  264. const zip = rows => rows[0].map((_, c) => rows.map(row => row[c]));
  265. for (const detail of zip([shopElements, shopLinks])) {
  266. detail[0].href = detail[1];
  267. }
  268. console.log('Links Rewrited');
  269. });
  270. break;
  271. default:
  272. break;
  273. }
  274. console.timeEnd('removeTracking');
  275. }
  276.  
  277. const ObserveOp = {
  278. LOADED: {
  279. FORM: Symbol(),
  280. IMAGE: Symbol(),
  281. HDTB: Symbol()
  282. },
  283. UPDATE: {
  284. HDTB: Symbol()
  285. },
  286. CHANGE: {
  287. HDTB: Symbol(),
  288. PAGE: Symbol()
  289. }
  290. };
  291. const ObserveDisconnectListAfTriggered = Object.values(ObserveOp.LOADED);
  292.  
  293. function startObserve(targetElement, op, func, conf = { childList: true }) {
  294. //console.log("Operation", op , "Register To", targetElement)
  295. new MutationObserver((mutations, observer) => {
  296. let nodes = Array.prototype.concat
  297. .apply([], mutations.map(s => Array.prototype.slice.call(s.addedNodes)))
  298. .filter(n => n.nodeName !== '#comment');
  299.  
  300. //console.log("Nodes Captured By", op, nodes);
  301.  
  302. switch (op) {
  303. case ObserveOp.LOADED.FORM:
  304. nodes = nodes.filter(n => n.name === 'gs_l');
  305. break;
  306. case ObserveOp.LOADED.IMAGE:
  307. nodes = nodes.filter(n => n.classList.contains('irc_bg'));
  308. break;
  309. case ObserveOp.LOADED.HDTB:
  310. nodes = nodes.filter(n => n.className === 'hdtb-mn-cont');
  311. break;
  312. case ObserveOp.UPDATE.HDTB:
  313. nodes = nodes.filter(n => n.className === 'hdtb-mn-cont');
  314. break;
  315. case ObserveOp.CHANGE.HDTB:
  316. nodes = nodes.filter(n => n.id === 'cnt');
  317. break;
  318. case ObserveOp.CHANGE.PAGE:
  319. nodes = nodes.filter(n => n.dataset && n.dataset.ved !== undefined);
  320. break;
  321. default:
  322. break;
  323. }
  324.  
  325. if (nodes.length >= 1) {
  326. //console.log("Operation", op , "Fired", nodes[0])
  327. func();
  328. if (ObserveDisconnectListAfTriggered.includes(op)) {
  329. observer.disconnect();
  330. }
  331. }
  332. }).observe(targetElement, conf);
  333. }
  334.  
  335. function pageInit() {
  336. removeTracking();
  337. startObserve($('#search'), ObserveOp.CHANGE.PAGE, removeTracking);
  338. }
  339.  
  340. const initMode = getMode();
  341. const confDeepObserve = { childList: true, subtree: true };
  342.  
  343. // Wait for .hdtb-mn-cont appears in the first page access
  344. if (lazy_hdtb && !legacy) {
  345. startObserve(
  346. root,
  347. ObserveOp.LOADED.HDTB,
  348. () => {
  349. switch (initMode) {
  350. case 'isch': // Image Search
  351. removeTracking();
  352. startObserve($('#isr_mc'), ObserveOp.LOADED.IMAGE, () => {
  353. $$(
  354. ".irc_tas, .irc_mil, .irc_hol, .irc_but[jsaction*='mousedown']"
  355. ).forEach(e => {
  356. e.__jsaction = null;
  357. e.removeAttribute('jsaction');
  358. });
  359. });
  360. startObserve(
  361. $('#top_nav'),
  362. ObserveOp.UPDATE.HDTB,
  363. removeTracking,
  364. confDeepObserve
  365. );
  366. break;
  367. default:
  368. pageInit();
  369. // Wait for #cnt inserted. In HDTB switching, since .hdtb-mn-cont does not appear
  370. startObserve(root, ObserveOp.CHANGE.HDTB, pageInit);
  371. break;
  372. }
  373. },
  374. confDeepObserve
  375. );
  376. }
  377.  
  378. if (legacy) {
  379. removeTracking();
  380.  
  381. // Remove unnecessary input
  382. startObserve(document.querySelector('form'), ObserveOp.LOADED.FORM, () => {
  383. document
  384. .querySelectorAll("form input:not([name='q']):not([name='hl'])")
  385. .forEach(s => removeDOM(s));
  386. });
  387.  
  388. // Remove unnecessary parameters from 'option'
  389. for(const option of document.querySelectorAll("#mor > option")){
  390. option.value = option.value.replace(regBadParameters, '');
  391. }
  392.  
  393. console.warn('legacy mode');
  394. console.timeEnd('LOAD');
  395. return;
  396. }
  397.  
  398. console.timeEnd('LOAD');
  399. }
  400.  
  401. function init() {
  402. console.time('init');
  403. onDeclare(window, 'google', 20).then(() => {
  404. rewriteProperties([
  405. [google, 'log', yesman],
  406. [google, 'rll', yesman],
  407. [google, 'logUrl', tired],
  408. [google, 'getEI', yesman],
  409. [google, 'getLEI', yesman],
  410. [google, 'ctpacw', yesman],
  411. [google, 'csiReport', yesman],
  412. [google, 'report', yesman],
  413. [google, 'aft', yesman],
  414. [google, 'kEI', '0']
  415. ]);
  416. });
  417.  
  418. // Reject Request by img tag
  419. const regBadImageSrc = /\/(?:gen(?:erate)?|client)_204/;
  420. Object.defineProperty(window.Image.prototype, 'src', {
  421. set: function(url) {
  422. if (!regBadImageSrc.test(url)) {
  423. this.setAttribute('src', url);
  424. }
  425. }
  426. });
  427.  
  428. // Reject unknown parameters by script tag
  429. Object.defineProperty(window.HTMLScriptElement.prototype, 'src', {
  430. set: function(url) {
  431. this.setAttribute('src', url.replace(regBadParameters, ''));
  432. }
  433. });
  434.  
  435. // hook XHR
  436. const origOpen = XMLHttpRequest.prototype.open;
  437. window.XMLHttpRequest.prototype.open = function(act, path) {
  438. if (regBadPaths.test(path)) {
  439. return;
  440. }
  441. origOpen.apply(this, [act, path.replace(regBadParameters, '')]);
  442. };
  443.  
  444. // do not send referrer
  445. const noreferrerMeta = document.createElement('meta');
  446. noreferrerMeta.setAttribute('name', 'referrer');
  447. noreferrerMeta.setAttribute('content', 'no-referrer');
  448. document.querySelector('head').appendChild(noreferrerMeta);
  449.  
  450. console.timeEnd('init');
  451. }
  452.  
  453. /* Execute */
  454.  
  455. init();
  456. window.addEventListener('DOMContentLoaded', load);
  457.  
  458. // for older browser
  459. if (document.getElementById('universal') !== null) {
  460. load();
  461. }