remove google tracking UWAA

remove google tracking

当前为 2017-11-29 提交的版本,查看 最新版本

  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 = $$('#rso a.pstl');
  313. const shopImgElements = $$('#rso a.psliimg');
  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. // for (shopElements, shopLinks, shopImgElements, shopArrays) in zip(~)
  334. const shopElement = detail[0];
  335. const shopLink = detail[1];
  336. const shopImgElement = detail[2];
  337. const shopArray = detail[3];
  338.  
  339. // Overwrite link
  340. shopElement.href = shopImgElement.href = shopLink;
  341.  
  342. // Disable click actions
  343. //detail[0].__jsaction = null;
  344. //detail[0].removeAttribute("jsaction");
  345.  
  346. // Overwrite variables used when link clicked
  347. try {
  348. shopArray[3][0][1] = shopLink;
  349. shopArray[14][1] = shopLink;
  350. shopArray[89][16] = shopLink;
  351. shopArray[89][18][0] = shopLink;
  352. shopArray[85][3] = shopLink;
  353. } catch (e) {}
  354. }
  355. console.log('Links Rewrited');
  356. });
  357. }
  358. };
  359.  
  360. function removeTracking() {
  361. console.time('removeTracking');
  362. const searchMode = getSearchMode();
  363. const badAttrNames = badAttrNamesObj[searchMode]
  364. ? badAttrNamesObj[searchMode]
  365. : badAttrNamesObj['default'];
  366. const directLinkParamName = 'q';
  367.  
  368. // search result
  369. for (const searchResult of $$(dirtySelector)) {
  370. // remove attributes
  371. for (const badAttrName of badAttrNames) {
  372. searchResult.removeAttribute(badAttrName);
  373. }
  374.  
  375. // hide referrer
  376. searchResult.rel = 'noreferrer';
  377.  
  378. // remove google redirect link(legacy)
  379. if (
  380. searchResult.hasAttribute('href') &&
  381. searchResult.getAttribute('href').startsWith('/url?')
  382. ) {
  383. searchResult.href = extractDirectLink(
  384. searchResult.href,
  385. directLinkParamName
  386. );
  387. }
  388. searchResult.href = searchResult.href.replace(regBadParameters, '');
  389. }
  390.  
  391. removeBadParameters();
  392.  
  393. searchMode in specProcesses && specProcesses[searchMode]();
  394.  
  395. console.timeEnd('removeTracking');
  396. }
  397.  
  398. const ObserveOp = {
  399. LOADED: {
  400. FORM: ['INPUT', 'name', /^oq$/],
  401. IMAGE: ['DIV', 'class', /.*irc_bg.*/],
  402. HDTB: ['DIV', 'class', /^hdtb-mn-cont$/]
  403. },
  404. UPDATE: {
  405. HDTB: ['DIV', 'class', /^hdtb-mn-cont$/]
  406. },
  407. CHANGE: {
  408. HDTB: ['DIV', 'id', /^cnt$/],
  409. PAGE: ['DIV', 'data-set', /.+/]
  410. }
  411. };
  412.  
  413. const ObserveUntilLoadedList = Object.values(ObserveOp.LOADED);
  414.  
  415. function startObserve(targetElement, op, func, conf = { childList: true }) {
  416. if (targetElement === null) {
  417. console.warn('targetElement is null', op, func);
  418. return;
  419. }
  420. //console.log(op, 'Register To', targetElement);
  421. const targetElementName = op[0];
  422. const targetAttrName = op[1];
  423. const targetAttrValueReg = op[2];
  424. const filterFunc = n => {
  425. return (
  426. n.nodeName === targetElementName &&
  427. targetAttrValueReg.test(n.getAttribute(targetAttrName))
  428. );
  429. };
  430.  
  431. // if targetElement already appeared
  432. if (
  433. ObserveUntilLoadedList.includes(op) &&
  434. Array.prototype.slice
  435. .call(targetElement.querySelectorAll(targetElementName))
  436. .filter(filterFunc).length >= 1
  437. ) {
  438. //console.log(op, 'Register To', targetElement);
  439. func();
  440. return;
  441. }
  442.  
  443. new MutationObserver((mutations, observer) => {
  444. const nodes = Array.prototype.concat
  445. .apply([], mutations.map(s => Array.prototype.slice.call(s.addedNodes)))
  446. //.map((s)=>{console.log(s);return s})
  447. .filter(filterFunc);
  448.  
  449. if (nodes.length >= 1) {
  450. //console.log(targetElement, op, 'Fired', nodes[0], func);
  451. func();
  452. if (ObserveUntilLoadedList.includes(op)) {
  453. observer.disconnect();
  454. }
  455. //return startObserve;
  456. }
  457. }).observe(targetElement, conf);
  458. }
  459.  
  460. function pageInit() {
  461. removeTracking();
  462. startObserve($('#search'), ObserveOp.CHANGE.PAGE, removeTracking);
  463. }
  464.  
  465. const confDeepObserve = { childList: true, subtree: true };
  466.  
  467. // Remove unnecessary input
  468. startObserve(
  469. document.querySelector('form'),
  470. ObserveOp.LOADED.FORM,
  471. removeFormInputs
  472. );
  473.  
  474. // Wait for .hdtb-mn-cont appears in the first page access
  475. if (lazy_hdtb && !legacy) {
  476. startObserve(
  477. root,
  478. ObserveOp.LOADED.HDTB,
  479. () => {
  480. // hdtb loaded
  481. switch (getSearchMode()) {
  482. case 'isch': // Image Search
  483. removeTracking();
  484.  
  485. // Remove unnecessary script from buttons
  486. startObserve($('#isr_mc'), ObserveOp.LOADED.IMAGE, () => {
  487. for (const node of $$(
  488. 'a.irc_tas, a.irc_mil, a.irc_hol, a.irc_but'
  489. )) {
  490. node.__jsaction = null;
  491. node.removeAttribute('jsaction');
  492. }
  493. });
  494.  
  495. // on search options updated
  496. startObserve(
  497. $('#top_nav'),
  498. ObserveOp.UPDATE.HDTB,
  499. removeBadParameters,
  500. confDeepObserve
  501. );
  502. break;
  503. default:
  504. pageInit();
  505. // Wait for #cnt inserted. In HDTB switching, since .hdtb-mn-cont does not appear
  506. startObserve(root, ObserveOp.CHANGE.HDTB, pageInit);
  507. break;
  508. }
  509. removeFormInputs();
  510. },
  511. confDeepObserve
  512. );
  513. } else if (legacy) {
  514. removeTracking();
  515.  
  516. // Remove unnecessary parameters from hdtb
  517. const hdtbRoot = $('#hdtbMenus');
  518. if (hdtbRoot) {
  519. startObserve(hdtbRoot, ObserveOp.LOADED.HDTB, removeBadParameters);
  520. }
  521.  
  522. if (document.getElementById('hdr')) {
  523. const stopAddParams = s => {
  524. const src = s.srcElement;
  525. if (src.nodeName === 'A' && src.href.match(/\/search.*[?&]tbm=isch/)) {
  526. s.stopPropagation();
  527. }
  528. };
  529. document.addEventListener('click', stopAddParams, true);
  530. document.addEventListener('touchStart', stopAddParams, true);
  531. }
  532.  
  533. // Remove unnecessary parameters from 'option'
  534. for (const option of document.querySelectorAll('#mor > option')) {
  535. option.value = option.value.replace(regBadParameters, '');
  536. }
  537.  
  538. console.warn('legacy mode');
  539. console.timeEnd('LOAD');
  540. return;
  541. }
  542.  
  543. console.timeEnd('LOAD');
  544. }
  545.  
  546. function init() {
  547. onDeclare(window, 'google', 20).then(() => {
  548. rewriteProperties([
  549. [google, 'log', yesman],
  550. [google, 'rll', yesman],
  551. [google, 'logUrl', tired],
  552. [google, 'getEI', yesman],
  553. [google, 'getLEI', yesman],
  554. [google, 'ctpacw', yesman],
  555. [google, 'csiReport', yesman],
  556. [google, 'report', yesman],
  557. [google, 'aft', yesman],
  558. [google, 'kEI', '0']
  559. ]);
  560. });
  561.  
  562. // Reject Request by img tag
  563. //maps:log204
  564. const regBadImageSrc = /\/(?:(?:gen(?:erate)?|client|fp)_|log)204|(?:metric|csi)\.gstatic\.|(?:adservice)\.(google)/;
  565. Object.defineProperty(window.Image.prototype, 'src', {
  566. set: function(url) {
  567. if (!regBadImageSrc.test(url)) {
  568. this.setAttribute('src', url);
  569. }
  570. }
  571. });
  572.  
  573. // Reject unknown parameters by script tag
  574. Object.defineProperty(window.HTMLScriptElement.prototype, 'src', {
  575. set: function(url) {
  576. this.setAttribute('src', url.replace(regBadParameters, ''));
  577. }
  578. });
  579.  
  580. // hook XHR
  581. const origOpen = XMLHttpRequest.prototype.open;
  582. window.XMLHttpRequest.prototype.open = function(act, path) {
  583. if (!regBadPaths.test(path)) {
  584. origOpen.apply(this, [act, path.replace(regBadParameters, '')]);
  585. }
  586. };
  587.  
  588. // beacon
  589. if ('navigator' in window) {
  590. const origSendBeacon = navigator.sendBeacon.bind(navigator);
  591. navigator.sendBeacon = (path, data) => {
  592. if (!regBadImageSrc.test(path)) {
  593. origSendBeacon(path, data);
  594. }
  595. };
  596. }
  597. }
  598.  
  599. /* Execute */
  600.  
  601. init();
  602. console.timeEnd('init');
  603.  
  604. if (
  605. location.pathname !== '/' &&
  606. location.pathname !== '/search' &&
  607. document.querySelector('html').getAttribute('itemtype') !==
  608. 'http://schema.org/SearchResultsPage'
  609. ) {
  610. console.warn('');
  611. return;
  612. }
  613.  
  614. window.addEventListener('DOMContentLoaded', load);
  615.  
  616. // for older browser
  617. if (document.getElementById('universal') !== null) {
  618. load();
  619. }