remove google tracking UWAA

remove google tracking

当前为 2018-07-25 提交的版本,查看 最新版本

  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. 'iact',
  75. 'forward',
  76. 'ndsp',
  77. 'csi',
  78. 'tbnid'
  79. //'docid', // related images
  80. //'imgdii', // related images
  81. ],
  82. searchform: [
  83. // search form
  84. 'pbx',
  85. 'dpr',
  86. 'pf',
  87. 'gs_rn',
  88. 'gs_mss',
  89. 'pq',
  90. 'cp',
  91. 'oq',
  92. 'sclient',
  93. 'gs_l',
  94. 'aqs'
  95. //'gs_ri', // suggestions
  96. //'gs_id', // suggestions
  97. //'xhr', // suggestions at image search
  98. //'tch', // js flag?
  99. ],
  100. // Google maps
  101. maps: ['psi']
  102. };
  103.  
  104. // search option on first access
  105. const GoogleOp = {
  106. maps: Symbol(),
  107. isch: Symbol(),
  108. search: Symbol(),
  109. unknown: Symbol()
  110. };
  111.  
  112. const op = (() => {
  113. if (location.pathname.startsWith('/maps')) {
  114. return GoogleOp.maps;
  115. }
  116. if (getSearchMode() === 'isch') {
  117. return GoogleOp.isch;
  118. } else {
  119. return GoogleOp.search;
  120. }
  121. })();
  122.  
  123. const badParametersNames = (() => {
  124. switch (op) {
  125. case GoogleOp.maps:
  126. return badParametersNamesObj.maps;
  127. case GoogleOp.isch:
  128. return badParametersNamesObj.base.concat(
  129. badParametersNamesObj.searchform,
  130. badParametersNamesObj.isch
  131. );
  132. case GoogleOp.search:
  133. return badParametersNamesObj.base.concat(
  134. badParametersNamesObj.searchform
  135. );
  136. }
  137. })();
  138.  
  139. const badAttrNamesObj = {
  140. default: ['onmousedown', 'ping', 'oncontextmenu'],
  141. search: ['onmousedown', 'ping', 'oncontextmenu'],
  142. vid: ['onmousedown'],
  143. nws: ['onmousedown'],
  144. bks: [],
  145. isch: [],
  146. shop: []
  147. };
  148.  
  149. // From the nodes selected here, delete parameters specified by badParametersNames
  150. const dirtyLinkSelectors = [
  151. // menu
  152. 'a.q.qs',
  153.  
  154. // doodle
  155. 'a.doodle',
  156.  
  157. // Upper left menu
  158. '.gb_Z > a',
  159.  
  160. // Logo
  161. 'a#logo',
  162. 'div #logocont > a',
  163. 'div#qslc > a',
  164. 'header#hdr > div > a',
  165.  
  166. // search button?
  167. 'form#sf > a',
  168.  
  169. /// imagesearch
  170. // colors
  171. 'div#sc-block > div > a',
  172. // size
  173. 'a.hdtb-mitem'
  174. ];
  175.  
  176. const badPaths = ['imgevent', 'shopping\\/product\\/.*?\\/popout'];
  177.  
  178. /* Compile */
  179. // The first paramater is probably 'q' so '?' does not consider
  180. const regBadParameters = new RegExp(
  181. '&(?:' + badParametersNames.join('|') + ')=.*?(?=(&|$))',
  182. 'g'
  183. );
  184. const regBadPaths = new RegExp('^/(?:' + badPaths.join('|') + ')');
  185. const dirtyLinkSelector = dirtyLinkSelectors
  186. .map(s => s + ":not([href=''])")
  187. .join(',');
  188.  
  189. /* Return parameter value */
  190. function extractDirectLink(str, param) {
  191. //(?<=q=)(.*)(?=&)/
  192. const res = new RegExp(`[?&]${param}(=([^&#]*))`).exec(str);
  193. if (!res || !res[2]) return '';
  194. return decodeURIComponent(res[2]);
  195. }
  196.  
  197. function sleep(ms) {
  198. return new Promise(resolve => setTimeout(resolve, ms));
  199. }
  200.  
  201. /* Return Promise when declared the variable name specified by argument */
  202. function onDeclare(obj, propertyStr, interval = 80) {
  203. return new Promise(async function(resolve, reject) {
  204. const propertyNames = propertyStr.split('.');
  205. let currObj = obj;
  206. for (const propertyName of propertyNames) {
  207. while (!(propertyName in currObj) || currObj[propertyName] === null) {
  208. await sleep(interval);
  209. }
  210. currObj = currObj[propertyName];
  211. }
  212. resolve(currObj);
  213. });
  214. }
  215.  
  216. function rewriteProperties(prop) {
  217. for (const table of prop) {
  218. //const targetObject = typeof table[0] === 'function' ? table[0]() : table[0];
  219. Object.defineProperty(table[0] || {}, table[1], {
  220. value: table[2],
  221. writable: false
  222. });
  223. }
  224. }
  225.  
  226. function load() {
  227. console.time('LOAD');
  228.  
  229. /* Overwrite disturbing functions */
  230. rewriteProperties([[window, 'rwt', yesman], [window.gbar_, 'Rm', yesman]]);
  231.  
  232. // do not send referrer
  233. const noreferrerMeta = document.createElement('meta');
  234. noreferrerMeta.setAttribute('name', 'referrer');
  235. noreferrerMeta.setAttribute('content', 'no-referrer');
  236. document.querySelector('head').appendChild(noreferrerMeta);
  237.  
  238. /*
  239. * Variables
  240. */
  241. // Whether to use AJAX
  242. const legacy = document.getElementById('cst') === null;
  243.  
  244. /* Nodes */
  245. const nodeMain = document.getElementById('main');
  246. const nodeCnt = document.getElementById('cnt');
  247. const root = (() => {
  248. if (legacy) {
  249. return nodeCnt || nodeMain || window.document;
  250. } else {
  251. return nodeMain; // || nodeCnt;
  252. }
  253. })();
  254.  
  255. // Flag indicating whether the hard tab is loaded on 'DOMContentLoaded'
  256. const lazy_hdtb = !legacy || root === nodeCnt;
  257.  
  258. // Define selector function
  259. const $ = root.querySelector.bind(root);
  260. const $$ = sel =>
  261. Array.prototype.slice.call(root.querySelectorAll.call(root, [sel]));
  262.  
  263. // Selector pointing to anchors to purify
  264. const dirtySelector = (() => {
  265. if (root === window.document) {
  266. return 'body a';
  267. } else if (legacy) {
  268. return `#${root.id} a`;
  269. } else {
  270. return '#rcnt a';
  271. }
  272. })();
  273.  
  274. // List of parameters to keep
  275. const saveParamNames = [
  276. 'q',
  277. 'hl',
  278. 'num',
  279. 'tbm',
  280. 'tbs',
  281. 'lr',
  282. 'btnI',
  283. 'btnK',
  284. 'safe'
  285. ];
  286. const obstacleInputsSelector =
  287. 'form[id*=sf] input' +
  288. saveParamNames.map(s => ':not([name=' + s + '])').join('');
  289.  
  290. /*
  291. * Functions
  292. */
  293. function removeFormInputs() {
  294. for (const node of document.querySelectorAll(obstacleInputsSelector)) {
  295. node.parentNode.removeChild(node);
  296. }
  297. }
  298.  
  299. function removeBadParameters() {
  300. for (const dirtyLink of document.querySelectorAll(dirtyLinkSelector)) {
  301. dirtyLink.href = dirtyLink.href.replace(regBadParameters, '');
  302. }
  303. }
  304.  
  305. const specProcesses = {
  306. shop: function() {
  307. // Overwrite links(desktop version only)
  308. //Object.values(google.pmc.smpo.r).map(s=>{return {title:s[14][0],link:s[28][8]}})
  309. if (legacy) return;
  310. onDeclare(google, 'pmc.spop.r').then(shopObj => {
  311. const _tempAnchors = $$(".sh-dlr__content a[jsaction='spop.c']");
  312. const [shopAnchors, shopThumbnailAnchors] = [0, 1].map(m =>
  313. _tempAnchors.filter((_, i) => i % 2 === m)
  314. );
  315. const shopArrays = Object.values(shopObj);
  316. const shopLinks = shopArrays.map(a => a[34][6]);
  317. const zip = rows => rows[0].map((_, c) => rows.map(row => row[c]));
  318.  
  319. if (shopAnchors.length !== shopLinks.length) {
  320. console.warn(
  321. 'length does not match',
  322. shopAnchors.length,
  323. shopLinks.length
  324. );
  325. return;
  326. }
  327.  
  328. for (const detail of zip([
  329. shopAnchors,
  330. shopLinks,
  331. shopThumbnailAnchors,
  332. shopArrays
  333. ])) {
  334. const [shopAnchor, shopLink, shopThumbnailAnchor, shopArray] = detail;
  335.  
  336. shopAnchor.href = shopThumbnailAnchor.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, 'logUrl', tired],
  545. [google, 'getEI', yesman],
  546. [google, 'getLEI', yesman],
  547. [google, 'ctpacw', yesman],
  548. [google, 'csiReport', yesman],
  549. [google, 'report', yesman],
  550. [google, 'aft', yesman],
  551. [google, 'kEI', '0']
  552. ]);
  553. });
  554.  
  555. // Reject Request by img tag
  556. //maps:log204
  557. const regBadImageSrc = /\/(?:(?:gen(?:erate)?|client|fp)_|log)204|(?:metric|csi)\.gstatic\.|(?:adservice)\.(google)/;
  558. Object.defineProperty(window.Image.prototype, 'src', {
  559. set: function(url) {
  560. if (!regBadImageSrc.test(url)) {
  561. this.setAttribute('src', url);
  562. }
  563. }
  564. });
  565.  
  566. // Reject unknown parameters by script tag
  567. Object.defineProperty(window.HTMLScriptElement.prototype, 'src', {
  568. set: function(url) {
  569. this.setAttribute('src', url.replace(regBadParameters, ''));
  570. }
  571. });
  572.  
  573. // hook XHR
  574. const origOpen = XMLHttpRequest.prototype.open;
  575. window.XMLHttpRequest.prototype.open = function(act, path) {
  576. if (!regBadPaths.test(path)) {
  577. origOpen.apply(this, [act, path.replace(regBadParameters, '')]);
  578. }
  579. };
  580.  
  581. // beacon
  582. if ('navigator' in window) {
  583. const origSendBeacon = navigator.sendBeacon.bind(navigator);
  584. navigator.sendBeacon = (path, data) => {
  585. if (!regBadImageSrc.test(path)) {
  586. origSendBeacon(path, data);
  587. }
  588. };
  589. }
  590. }
  591.  
  592. /* Execute */
  593.  
  594. init();
  595. console.timeEnd('init');
  596.  
  597. if (
  598. location.pathname !== '/' &&
  599. location.pathname !== '/search' &&
  600. document.querySelector('html').getAttribute('itemtype') !==
  601. 'http://schema.org/SearchResultsPage'
  602. ) {
  603. console.warn('');
  604. return;
  605. }
  606.  
  607. window.addEventListener('DOMContentLoaded', load);
  608.  
  609. // for older browser
  610. if (document.getElementById('universal') !== null) {
  611. load();
  612. }