remove google tracking UWAA

remove google tracking

当前为 2018-02-03 提交的版本,查看 最新版本

  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.8
  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. console.time('init');
  22.  
  23. try {
  24. window = window.unsafeWindow || window;
  25. } catch (e) {}
  26.  
  27. const yesman = function() {
  28. return true;
  29. };
  30. const tired = function() {};
  31.  
  32. /* Return the current Google search mode */
  33. function getParam(parameter, name) {
  34. var results = new RegExp('[?&]' + name + '=([^&#]*)').exec(parameter);
  35. if (results === null) {
  36. return null;
  37. } else {
  38. return results.pop() || 0;
  39. }
  40. }
  41.  
  42. /* return search mode */
  43. function getSearchMode() {
  44. const parameter = location.search + location.hash;
  45. return getParam(parameter, 'tbm') || 'search';
  46. }
  47.  
  48. // matching tracking paramaters
  49. const badParametersNamesObj = {
  50. base: [
  51. 'biw', // offsetWidth
  52. 'bih', // offsetHeight
  53. 'ei',
  54. 'sa',
  55. 'ved',
  56. 'source',
  57. 'prds',
  58. 'bvm',
  59. 'bav',
  60. 'psi',
  61. 'stick',
  62. 'dq',
  63. 'ech',
  64. 'gs_gbg',
  65. 'gs_rn',
  66. 'cp',
  67. 'ictx'
  68. ],
  69. // image search
  70. isch: [
  71. 'scroll',
  72. 'vet',
  73. 'yv',
  74. 'ijn',
  75. 'iact',
  76. 'forward',
  77. 'ndsp',
  78. 'csi',
  79. 'tbnid'
  80. //'docid', // related images
  81. //'imgdii', // related images
  82. ],
  83. searchform: [
  84. // search form
  85. 'pbx',
  86. 'dpr',
  87. 'pf',
  88. 'gs_rn',
  89. 'gs_mss',
  90. 'pq',
  91. 'cp',
  92. 'oq',
  93. 'sclient',
  94. 'gs_l',
  95. 'aqs'
  96. //'gs_ri', // suggestions
  97. //'gs_id', // suggestions
  98. //'xhr', // suggestions at image search
  99. //'tch', // js flag?
  100. ],
  101. // Google maps
  102. maps: ['psi']
  103. };
  104.  
  105. // search option on first access
  106. const GoogleOp = {
  107. maps: Symbol(),
  108. isch: Symbol(),
  109. search: Symbol(),
  110. unknown: Symbol()
  111. };
  112.  
  113. const op = (() => {
  114. if (location.pathname.startsWith('/maps')) {
  115. return GoogleOp.maps;
  116. }
  117. if (getSearchMode() === 'isch') {
  118. return GoogleOp.isch;
  119. } else {
  120. return GoogleOp.search;
  121. }
  122. })();
  123.  
  124. const badParametersNames = (() => {
  125. switch (op) {
  126. case GoogleOp.maps:
  127. return badParametersNamesObj.maps;
  128. case GoogleOp.isch:
  129. return badParametersNamesObj.base.concat(
  130. badParametersNamesObj.searchform,
  131. badParametersNamesObj.isch
  132. );
  133. case GoogleOp.search:
  134. return badParametersNamesObj.base.concat(
  135. badParametersNamesObj.searchform
  136. );
  137. }
  138. })();
  139.  
  140. const badAttrNamesObj = {
  141. default: ['onmousedown', 'ping', 'oncontextmenu'],
  142. search: ['onmousedown', 'ping', 'oncontextmenu'],
  143. vid: ['onmousedown'],
  144. nws: ['onmousedown'],
  145. bks: [],
  146. isch: [],
  147. shop: []
  148. };
  149.  
  150. // From the nodes selected here, delete parameters specified by badParametersNames
  151. const dirtyLinkSelectors = [
  152. // menu
  153. 'a.q.qs',
  154.  
  155. // doodle
  156. 'a.doodle',
  157.  
  158. // Upper left menu
  159. '.gb_Z > a',
  160.  
  161. // Logo
  162. 'a#logo',
  163. 'div #logocont > a',
  164. 'div#qslc > a',
  165. 'header#hdr > div > a',
  166.  
  167. // search button?
  168. 'form#sf > a',
  169.  
  170. /// imagesearch
  171. // colors
  172. 'div#sc-block > div > a',
  173. // size
  174. 'a.hdtb-mitem'
  175. ];
  176.  
  177. const badPaths = ['imgevent', 'shopping\\/product\\/.*?\\/popout'];
  178.  
  179. /* Compile */
  180. // The first paramater is probably 'q' so '?' does not consider
  181. const regBadParameters = new RegExp(
  182. '&(?:' + badParametersNames.join('|') + ')=.*?(?=(&|$))',
  183. 'g'
  184. );
  185. const regBadPaths = new RegExp('^/(?:' + badPaths.join('|') + ')');
  186. const dirtyLinkSelector = dirtyLinkSelectors
  187. .map(s => s + ":not([href=''])")
  188. .join(',');
  189.  
  190. /* Return parameter value */
  191. function extractDirectLink(str, param) {
  192. //(?<=q=)(.*)(?=&)/
  193. const res = new RegExp(`[?&]${param}(=([^&#]*))`).exec(str);
  194. if (!res || !res[2]) return '';
  195. return decodeURIComponent(res[2]);
  196. }
  197.  
  198. function sleep(ms) {
  199. return new Promise(resolve => setTimeout(resolve, ms));
  200. }
  201.  
  202. /* Return Promise when declared the variable name specified by argument */
  203. function onDeclare(obj, propertyStr, interval = 80) {
  204. return new Promise(async function(resolve, reject) {
  205. const propertyNames = propertyStr.split('.');
  206. let currObj = obj;
  207. for (const propertyName of propertyNames) {
  208. while (!(propertyName in currObj) || currObj[propertyName] === null) {
  209. await sleep(interval);
  210. }
  211. currObj = currObj[propertyName];
  212. }
  213. resolve(currObj);
  214. });
  215. }
  216.  
  217. function rewriteProperties(prop) {
  218. for (const table of prop) {
  219. //const targetObject = typeof table[0] === 'function' ? table[0]() : table[0];
  220. Object.defineProperty(table[0] || {}, table[1], {
  221. value: table[2],
  222. writable: false
  223. });
  224. }
  225. }
  226.  
  227. function load() {
  228. console.time('LOAD');
  229.  
  230. /* Overwrite disturbing functions */
  231. rewriteProperties([[window, 'rwt', yesman], [window.gbar_, 'Rm', yesman]]);
  232.  
  233. // do not send referrer
  234. const noreferrerMeta = document.createElement('meta');
  235. noreferrerMeta.setAttribute('name', 'referrer');
  236. noreferrerMeta.setAttribute('content', 'no-referrer');
  237. document.querySelector('head').appendChild(noreferrerMeta);
  238.  
  239. /*
  240. * Variables
  241. */
  242. // Whether to use AJAX
  243. const legacy = document.getElementById('cst') === null;
  244.  
  245. /* Nodes */
  246. const nodeMain = document.getElementById('main');
  247. const nodeCnt = document.getElementById('cnt');
  248. const root = (() => {
  249. if (legacy) {
  250. return nodeCnt || nodeMain || window.document;
  251. } else {
  252. return nodeMain; // || nodeCnt;
  253. }
  254. })();
  255.  
  256. // Flag indicating whether the hard tab is loaded on 'DOMContentLoaded'
  257. const lazy_hdtb = !legacy || root === nodeCnt;
  258.  
  259. // Define selector function
  260. const $ = root.querySelector.bind(root);
  261. const $$ = sel =>
  262. Array.prototype.slice.call(root.querySelectorAll.call(root, [sel]));
  263.  
  264. // Selector pointing to anchors to purify
  265. const dirtySelector = (() => {
  266. if (root === window.document) {
  267. return 'body a';
  268. } else if (legacy) {
  269. return `#${root.id} a`;
  270. } else {
  271. return '#rcnt a';
  272. }
  273. })();
  274.  
  275. // List of parameters to keep
  276. const saveParamNames = [
  277. 'q',
  278. 'hl',
  279. 'num',
  280. 'tbm',
  281. 'tbs',
  282. 'lr',
  283. 'btnI',
  284. 'btnK',
  285. 'safe'
  286. ];
  287. const obstacleInputsSelector =
  288. 'form[id*=sf] input' +
  289. saveParamNames.map(s => ':not([name=' + s + '])').join('');
  290.  
  291. /*
  292. * Functions
  293. */
  294. function removeFormInputs() {
  295. for (const node of document.querySelectorAll(obstacleInputsSelector)) {
  296. node.parentNode.removeChild(node);
  297. }
  298. }
  299.  
  300. function removeBadParameters() {
  301. for (const dirtyLink of document.querySelectorAll(dirtyLinkSelector)) {
  302. dirtyLink.href = dirtyLink.href.replace(regBadParameters, '');
  303. }
  304. }
  305.  
  306. const specProcesses = {
  307. shop: function() {
  308. // Overwrite links(desktop version only)
  309. //Object.values(google.pmc.smpo.r).map(s=>{return {title:s[14][0],link:s[28][8]}})
  310. if (legacy) return;
  311. onDeclare(google, 'pmc.spop.r').then(shopObj => {
  312. const shopElements = $$(".sh-dlr__content>div:nth-child(2)>div>div:nth-child(1)>div:nth-child(1)>a");
  313. const shopImgElements = $$("#rso .sh-dlr__thumbnail");
  314. const shopArrays = Object.values(shopObj);
  315. const shopLinks = shopArrays.map(a => a[34][6]);
  316. const zip = rows => rows[0].map((_, c) => rows.map(row => row[c]));
  317.  
  318. if (shopElements.length !== shopLinks.length) {
  319. console.warn(
  320. 'length does not match',
  321. shopElements.length,
  322. shopLinks.length
  323. );
  324. return;
  325. }
  326.  
  327. for (const detail of zip([
  328. shopElements,
  329. shopLinks,
  330. shopImgElements,
  331. shopArrays
  332. ])) {
  333. const [shopElement,shopLink,shopImgElement,shopArray] = detail;
  334.  
  335. // Overwrite link
  336. shopElement.href = shopImgElement.href = shopLink;
  337.  
  338. // Disable click actions
  339. //detail[0].__jsaction = null;
  340. //detail[0].removeAttribute("jsaction");
  341.  
  342. // Overwrite variables used when link clicked
  343. try {
  344. shopArray[3][0][1] = shopLink;
  345. shopArray[14][1] = shopLink;
  346. shopArray[89][16] = shopLink;
  347. shopArray[89][18][0] = shopLink;
  348. shopArray[85][3] = shopLink;
  349. } catch (e) {}
  350. }
  351. console.log('Links Rewrited');
  352. });
  353. }
  354. };
  355.  
  356. function removeTracking() {
  357. console.time('removeTracking');
  358. const searchMode = getSearchMode();
  359. const badAttrNames = badAttrNamesObj[searchMode]
  360. ? badAttrNamesObj[searchMode]
  361. : badAttrNamesObj['default'];
  362. const directLinkParamName = 'q';
  363.  
  364. // search result
  365. for (const searchResult of $$(dirtySelector)) {
  366. // remove attributes
  367. for (const badAttrName of badAttrNames) {
  368. searchResult.removeAttribute(badAttrName);
  369. }
  370.  
  371. // hide referrer
  372. searchResult.rel = 'noreferrer';
  373.  
  374. // remove google redirect link(legacy)
  375. if (
  376. searchResult.hasAttribute('href') &&
  377. searchResult.getAttribute('href').startsWith('/url?')
  378. ) {
  379. searchResult.href = extractDirectLink(
  380. searchResult.href,
  381. directLinkParamName
  382. );
  383. }
  384. searchResult.href = searchResult.href.replace(regBadParameters, '');
  385. }
  386.  
  387. removeBadParameters();
  388.  
  389. searchMode in specProcesses && specProcesses[searchMode]();
  390.  
  391. console.timeEnd('removeTracking');
  392. }
  393.  
  394. const ObserveOp = {
  395. LOADED: {
  396. FORM: ['INPUT', 'name', /^oq$/],
  397. IMAGE: ['DIV', 'class', /.*irc_bg.*/],
  398. HDTB: ['DIV', 'class', /^hdtb-mn-cont$/]
  399. },
  400. UPDATE: {
  401. HDTB: ['DIV', 'class', /^hdtb-mn-cont$/]
  402. },
  403. CHANGE: {
  404. HDTB: ['DIV', 'id', /^cnt$/],
  405. PAGE: ['DIV', 'data-set', /.+/]
  406. }
  407. };
  408.  
  409. const ObserveUntilLoadedList = Object.values(ObserveOp.LOADED);
  410.  
  411. function startObserve(targetElement, op, func, conf = { childList: true }) {
  412. if (targetElement === null) {
  413. console.warn('targetElement is null', op, func);
  414. return;
  415. }
  416. //console.log(op, 'Register To', targetElement);
  417. const targetElementName = op[0];
  418. const targetAttrName = op[1];
  419. const targetAttrValueReg = op[2];
  420. const filterFunc = n => {
  421. return (
  422. n.nodeName === targetElementName &&
  423. targetAttrValueReg.test(n.getAttribute(targetAttrName))
  424. );
  425. };
  426.  
  427. // if targetElement already appeared
  428. if (
  429. ObserveUntilLoadedList.includes(op) &&
  430. Array.prototype.slice
  431. .call(targetElement.querySelectorAll(targetElementName))
  432. .filter(filterFunc).length >= 1
  433. ) {
  434. //console.log(op, 'Register To', targetElement);
  435. func();
  436. return;
  437. }
  438.  
  439. new MutationObserver((mutations, observer) => {
  440. const nodes = Array.prototype.concat
  441. .apply([], mutations.map(s => Array.prototype.slice.call(s.addedNodes)))
  442. //.map((s)=>{console.log(s);return s})
  443. .filter(filterFunc);
  444.  
  445. if (nodes.length >= 1) {
  446. //console.log(targetElement, op, 'Fired', nodes[0], func);
  447. func();
  448. if (ObserveUntilLoadedList.includes(op)) {
  449. observer.disconnect();
  450. }
  451. //return startObserve;
  452. }
  453. }).observe(targetElement, conf);
  454. }
  455.  
  456. function pageInit() {
  457. removeTracking();
  458. startObserve($('#search'), ObserveOp.CHANGE.PAGE, removeTracking);
  459. }
  460.  
  461. const confDeepObserve = { childList: true, subtree: true };
  462.  
  463. // Remove unnecessary input
  464. startObserve(
  465. document.querySelector('form'),
  466. ObserveOp.LOADED.FORM,
  467. removeFormInputs
  468. );
  469.  
  470. // Wait for .hdtb-mn-cont appears in the first page access
  471. if (lazy_hdtb && !legacy) {
  472. startObserve(
  473. root,
  474. ObserveOp.LOADED.HDTB,
  475. () => {
  476. // hdtb loaded
  477. switch (getSearchMode()) {
  478. case 'isch': // Image Search
  479. removeTracking();
  480.  
  481. // Remove unnecessary script from buttons
  482. startObserve($('#isr_mc'), ObserveOp.LOADED.IMAGE, () => {
  483. for (const node of $$("a[class*=irc_]")) {
  484. node.__jsaction = null;
  485. node.removeAttribute('jsaction');
  486. }
  487. });
  488.  
  489. // on search options updated
  490. startObserve(
  491. $('#top_nav'),
  492. ObserveOp.UPDATE.HDTB,
  493. removeBadParameters,
  494. confDeepObserve
  495. );
  496. break;
  497. default:
  498. pageInit();
  499. // Wait for #cnt inserted. In HDTB switching, since .hdtb-mn-cont does not appear
  500. startObserve(root, ObserveOp.CHANGE.HDTB, pageInit);
  501. break;
  502. }
  503. removeFormInputs();
  504. },
  505. confDeepObserve
  506. );
  507. } else if (legacy) {
  508. removeTracking();
  509.  
  510. // Remove unnecessary parameters from hdtb
  511. const hdtbRoot = $('#hdtbMenus');
  512. if (hdtbRoot) {
  513. startObserve(hdtbRoot, ObserveOp.LOADED.HDTB, removeBadParameters);
  514. }
  515.  
  516. if (document.getElementById('hdr')) {
  517. const stopAddParams = s => {
  518. const src = s.srcElement;
  519. if (src.nodeName === 'A' && src.href.match(/\/search.*[?&]tbm=isch/)) {
  520. s.stopPropagation();
  521. }
  522. };
  523. document.addEventListener('click', stopAddParams, true);
  524. document.addEventListener('touchStart', stopAddParams, true);
  525. }
  526.  
  527. // Remove unnecessary parameters from 'option'
  528. for (const option of document.querySelectorAll('#mor > option')) {
  529. option.value = option.value.replace(regBadParameters, '');
  530. }
  531.  
  532. console.warn('legacy mode');
  533. console.timeEnd('LOAD');
  534. return;
  535. }
  536.  
  537. console.timeEnd('LOAD');
  538. }
  539.  
  540. function init() {
  541. onDeclare(window, 'google', 20).then(() => {
  542. rewriteProperties([
  543. [google, 'log', yesman],
  544. [google, 'rll', yesman],
  545. [google, 'logUrl', tired],
  546. [google, 'getEI', yesman],
  547. [google, 'getLEI', yesman],
  548. [google, 'ctpacw', yesman],
  549. [google, 'csiReport', yesman],
  550. [google, 'report', yesman],
  551. [google, 'aft', yesman],
  552. [google, 'kEI', '0']
  553. ]);
  554. });
  555.  
  556. // Reject Request by img tag
  557. //maps:log204
  558. const regBadImageSrc = /\/(?:(?:gen(?:erate)?|client|fp)_|log)204|(?:metric|csi)\.gstatic\.|(?:adservice)\.(google)/;
  559. Object.defineProperty(window.Image.prototype, 'src', {
  560. set: function(url) {
  561. if (!regBadImageSrc.test(url)) {
  562. this.setAttribute('src', url);
  563. }
  564. }
  565. });
  566.  
  567. // Reject unknown parameters by script tag
  568. Object.defineProperty(window.HTMLScriptElement.prototype, 'src', {
  569. set: function(url) {
  570. this.setAttribute('src', url.replace(regBadParameters, ''));
  571. }
  572. });
  573.  
  574. // hook XHR
  575. const origOpen = XMLHttpRequest.prototype.open;
  576. window.XMLHttpRequest.prototype.open = function(act, path) {
  577. if (!regBadPaths.test(path)) {
  578. origOpen.apply(this, [act, path.replace(regBadParameters, '')]);
  579. }
  580. };
  581.  
  582. // beacon
  583. if ('navigator' in window) {
  584. const origSendBeacon = navigator.sendBeacon.bind(navigator);
  585. navigator.sendBeacon = (path, data) => {
  586. if (!regBadImageSrc.test(path)) {
  587. origSendBeacon(path, data);
  588. }
  589. };
  590. }
  591. }
  592.  
  593. /* Execute */
  594.  
  595. init();
  596. console.timeEnd('init');
  597.  
  598. if (
  599. location.pathname !== '/' &&
  600. location.pathname !== '/search' &&
  601. document.querySelector('html').getAttribute('itemtype') !==
  602. 'http://schema.org/SearchResultsPage'
  603. ) {
  604. console.warn('');
  605. return;
  606. }
  607.  
  608. window.addEventListener('DOMContentLoaded', load);
  609.  
  610. // for older browser
  611. if (document.getElementById('universal') !== null) {
  612. load();
  613. }