Yandex Extra Buttons

Add buttons (past 1/2/3 days, weeks, PDF search etc.) for Yandex search page

目前为 2021-01-11 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Yandex Extra Buttons
  3. // @name:ru Yandex_Extra_Buttons
  4. // @description Add buttons (past 1/2/3 days, weeks, PDF search etc.) for Yandex search page
  5. // @description:ru Кнопки вариантов поиска для страницы Yandex (1-2-3 дня, недели, PDF, ...)
  6. // @version 9.2021.1.111
  7. // @namespace spmbt.github.com
  8. // @icon //yastatic.net/islands-icons/_/aKnllxm-gQhidpzbZqub7qe641g.ico
  9. // @include https://yandex.*
  10. // @include https://www.yandex.*
  11. // @include https://yandex.*/search*
  12. // @include https://yandex.*/yandsearch*
  13. // @include https://spmbt.github.io/googleSearchExtraButtons/saveYourLocalStorage.html
  14. // @include https://www.gstatic.com/sites/p/b9356d/system/services/test.html
  15. // @include https://www.gstatic.com/index.html
  16. // @update buttons CSP fix for main page(native settings) (w/o authorization)
  17. // ==/UserScript==
  18. var xLocStI =0, xLocSto = [{origin:'https://spmbt.github.io', restHref:'/googleSearchExtraButtons/saveYourLocalStorage.html'},
  19. {origin:'https://www.gstatic.com', restHref:'/sites/p/b9356d/system/services/test.html', '//':'blank page'},
  20. {origin:'https://www.gstatic.com', restHref:'/index.html', '//':'404 page'}];
  21. // For use own eXternal LocalStorage add to array your origin+restHref of site with https protocol,
  22. // set xLocStI pointed to it, @include directive with this URL. If this script is Chrome extension, fill include_globs in manifest.json.
  23. // TODO If localStorage will be unavailable, script will be use next indexes of array.
  24. if(location.host == xLocSto[xLocStI].origin.replace(/[^/]*\/\//,'')){
  25. window.addEventListener('message', function(ev){
  26. //console.log('[io0]', ev.origin);
  27. if(/^https?:\/\/(www\.)?yandex\./.test(ev.origin)){
  28. var d = typeof ev.data =='string' && ev.data[0] =='{' ? JSON.parse(ev.data) : ev.data;
  29. if(!d.do) return;
  30. var tok = d.tok, key = d.key; try{
  31. switch(d.do){
  32. case 'set':
  33. var prev = localStorage[key];
  34. if(d.val !==undefined)
  35. localStorage[key] = JSON.stringify(d.val);
  36. else
  37. localStorage.removeItem(key);
  38. break;
  39. case 'get':
  40. prev = localStorage[key];
  41. prev = prev === undefined || typeof prev =='string'&& prev[0] !='{'? prev : JSON.parse(prev); break;
  42. case 'remove':
  43. prev = localStorage[key];
  44. if(prev !==undefined)
  45. localStorage.removeItem(key);
  46. }} catch(er){}
  47. xLocStI !=0 && console.log('[xLocSto]', tok, 'prev=', prev);
  48. xLocStI !=0 && ev.source.postMessage(JSON.stringify(prev !==undefined ? {tok: tok, prev: prev} : {tok: tok, undef:1}), ev.origin);
  49. //ev.source.postMessage(JSON.stringify(prev !==undefined ? {tok: tok, prev: prev} : {tok: tok, undef:1}), ev.origin);
  50. }},!1); console.log('[xLocSto-1]_'+ xLocStI);
  51. }else (function(setts){ //lang, sites, lastHoursLess
  52. if(window != top) return;
  53.  
  54. var $x = function(el, h){if(h) for(var i in h) el[i] = h[i]; return el;} //===extend===
  55. ,$pd = function(ev){ev.preventDefault();}
  56. ,d = document, S //current settings
  57. ,$q = function(q,el){return (el||d).querySelector(q)}
  58. ,$qA = function(q,el){return (el||d).querySelectorAll(q)}
  59. ,lh = location.href
  60. ,cspState //if 1 set constant setts
  61. ,$e = function(g,el){ //===create or use existing element=== //g={el|clone,cl,ht,cs,at,atRemove,on,apT}
  62. g.el = el || g.el || g.clone ||'DIV';
  63. var o = g.o = g.clone && g.clone.cloneNode && g.clone.cloneNode(!0)
  64. || (typeof g.el =='string' ? d.createElement(g.el) : g.el);
  65. if(o){ //execute if exist
  66. if(g.cl)
  67. o.className = g.cl;
  68. if(g.clRemove)
  69. o.classList.remove(g.clRemove);
  70. if(g.clAdd)
  71. o.classList.add(g.clAdd);
  72. if(g.cs)
  73. $x(o.style, g.cs);
  74. if(g.ht || g.at){
  75. var at = g.at ||{}; if(g.ht) at.innerHTML = g.ht;}
  76. if(at)
  77. for(var i in at){
  78. if(i=='innerHTML') o[i] = at[i];
  79. else o.setAttribute(i, at[i]);}
  80. if(g.atRemove)
  81. for(var i in g.atRemove)
  82. o.removeAttribute(g.atRemove[i]);
  83. if(g.on)
  84. for(var i in g.on) if(g.on[i])
  85. o.addEventListener(i, g.on[i],!1);
  86. g.ap && o.appendChild(g.ap);
  87. g.apT && g.apT.appendChild(o);
  88. }
  89. return o;
  90. },
  91. addRules = function(css){$e({apT: d.getElementsByTagName('head')[0], ap: d.createTextNode(css)},'style')}
  92. //check occurrence of third-party event with growing interval: h.t=time, h.i=count, h.c=check, h.o=occur, h.m=multi
  93. ,CS = function(h,d){d?h.o(d):h.i--&&setTimeout(function(){CS(h,h.c())},h.t*=h.m)} //example: t:120, i:12, m: 1.6 => wait around 55 sec
  94. //for xLocStor:
  95. ,xLocStorOrigin = d.location.protocol + xLocSto[xLocStI].origin.replace(/[^/]*/,'')
  96. ,qr, qrs ={} //set of queries "key-calls" (ок, toutLitt, toutLong, noService, noStorage)
  97. ,qrI = 0 //queries counter
  98. ,qrN = 12 //max number of waiting queries
  99. ,errIMax = 120, errNMax = errIMax //max number of errors
  100. ,ns ='googXButtons_' //namespace for keys
  101. ,listenMsg
  102. /**
  103. * external localStorage for using another domain if current domain storage is erased anywhere
  104. * @param{String} h.do - action: set|get|remove
  105. * @param{String} h.key
  106. * @param{Object|undefined} h.val (any type)
  107. * @param{Number|undefined} h.toutLitt
  108. * @param{Number|undefined} h.tout
  109. * @param{Function} h.cB - callback with 2 arguments
  110. * @param{Function|undefined} h.err - callback for err with one argument
  111. */
  112. ,xLocStor = function(h){
  113. var h0 = h;
  114. h.toutLitt = h.toutLitt || 400;
  115. h.tout = h.tout || 4000;
  116. var ifr = $q('#xLocStor')
  117. ,query = function(){
  118. if((qrI += 1) > qrN){
  119. xCatch('longQrs', null, h);
  120. return;}
  121. ifr.contentWindow.postMessage(JSON.stringify($x({
  122. do: h.do
  123. ,tok: token
  124. ,key: ns + h.key
  125. }, h.val !==undefined ? {val: h.val}:{}) )
  126. , xLocStorOrigin);
  127. qrs[token] = $x({ //for wait of response
  128. wToutLitt: (function(h, qrI, errIMax){return setTimeout(function(){
  129. qrI -= 1;
  130. if((errIMax -= 1) >=0)
  131. ;//console.warn('toutLitt', h);
  132. chkErrMax();
  133. }, h.toutLitt);})(h, qrI, errIMax)
  134. ,wTout: (function(h, qrI){return setTimeout(function(){
  135. qrI -= 1;
  136. //xCatch('tout', null, h);
  137. //xLocStor(h0);
  138. }, h.tout);})(h, qrI)
  139. }, h);
  140. }
  141. ,token = +new Date() + (Math.random()+'').substr(1,8)
  142. ,el = h.el;
  143. delete h.el;
  144. /*
  145. //csp in main page
  146. media-src yastatic.net kiks.yandex.ru;
  147. img-src 'self' data: https://yastatic.net https://home.yastatic.net https://*.yandex.ru https://*.yandex.net
  148. https://*.tns-counter.ru yastatic.net home.yastatic.net yandex.ru *.yandex.ru *.yandex.net *.tns-counter.ru *.gemius.pl yandex.st;
  149. font-src 'self' https://yastatic.net yastatic.net;
  150. connect-src 'self' wss://push.yandex.ru wss://portal-xiva.yandex.net https://yastatic.net https://home.yastatic.net
  151. https://yandex.ru https://*.yandex.ru portal-xiva.yandex.net yastatic.net home.yastatic.net yandex.ru
  152. *.yandex.ru *.yandex.net yandex.st;
  153. script-src 'self' 'unsafe-inline' 'unsafe-eval' https://suburban-widget.rasp.yandex.ru https://suburban-widget.rasp.yandex.net
  154. https://yastatic.net https://home.yastatic.net https://mc.yandex.ru https://pass.yandex.ru yastatic.net
  155. home.yastatic.net yandex.ru www.yandex.ru mc.yandex.ru suggest.yandex.ru clck.yandex.ru awaps.yandex.net;
  156. default-src 'self' wss://portal-xiva.yandex.net portal-xiva.yandex.net;
  157. style-src 'self' 'unsafe-inline' https://yastatic.net https://home.yastatic.net yastatic.net home.yastatic.net;
  158. frame-src 'self' https://yastatic.net https://yandex.ru https://*.yandex.ru wfarm.yandex.net yastatic.net
  159. yandex.ru *.yandex.ru awaps.yandex.net;
  160. report-uri https://csp.yandex.net/csp?from=big.ru&showid=22900.20964.1459066888.30083&h=n58&yandexuid=833832981443596954;
  161. object-src *.yandex.net yastatic.net kiks.yandex.ru awaps.yandex.net storage.mds.yandex.net;
  162.  
  163. //csp in results
  164. default-src 'self' 'unsafe-inline' 'unsafe-eval' data: https://!*.yandex.net:* *.yandex.net:* https://!*.yandex.ru:*
  165. *.yandex.ru:* https://yandex.ru:* yandex.ru:* https://yandex.st:* yandex.st:* yastatic.net https://yastatic.net
  166. *.tns-counter.ru https://!*.tns-counter.ru https://video.khl.ru https://www.video.khl.ru https://1tv.ru
  167. https://www.1tv.ru https://stream.1tv.ru https://www.stream.1tv.ru https://www.youtube.com https://video.kinopoisk.ru
  168. https://pbs.twimg.com yandex.ua https://yandex.ua *.yandex.ua https://!*.yandex.ua;
  169. report-uri https://csp.yandex.net/csp?from=web&reqid=1459037130208387-17346427857802980809255285-sas1-1677&yandexuid=833832981443596954&yandex_login=
  170. */
  171. //console.info('h.csp: ',h.csp)
  172. if(!h.csp){
  173. cspState =1;
  174. if(ifr){
  175. //ifr.src = xLocStorOrigin +'/googleSearchExtraButtons/saveYourLocalStorage.html?1'
  176. query();
  177. }
  178. else ifr = $e({
  179. el: 'iframe',
  180. at:{id: 'xLocStor'
  181. ,src: xLocStorOrigin + xLocSto[xLocStI].restHref},
  182. cs: {display: 'none'},
  183. on: {load: query},
  184. apT: el || d.body
  185. });
  186. setTimeout(function(){cspState =2;},0);
  187. if(!listenMsg) addEventListener('message', function(ev){
  188. if(ev.origin == xLocStorOrigin){ // {"tok":"<value>"[,"err":"<txt>"],"h":...}
  189. //console.log('from_io', JSON.parse(ev.data))
  190. var resp = ev.data && ev.data[0] =='{' && JSON.parse(ev.data);
  191. if(!resp) xCatch('bad_format', resp, h);
  192. if(( qr = qrs[resp.tok] )){
  193. qrI -= 1;
  194. qr.cB(resp.prev, resp.undef);
  195. var er = qr.err;
  196. delete qrs[resp.tok];} // else ignore unsufficient token
  197. if(resp.err && (!er || er(resp.err)) ) //individual or common error processing depends of er()
  198. xCatch(resp.err, resp, h);
  199. cspState =3;
  200. }},!1);
  201. }else{
  202. h.cB && h.cB(setts, 1);
  203. }
  204. listenMsg =1;
  205. },
  206. //for tests: localStorage.googXButtons_dwmyh = JSON.stringify({h:[1,2,1,1,1]})
  207. //$('#xLocStor').contentWindow.postMessage('{"do":"get","key":"googXButtons_dwmyh"}',xLocSto[xLocStI].origin)
  208. xCatch = function(er, resp, h){
  209. if((errIMax -= 1) >=0)
  210. console.error('tok:', resp && resp.tok ||'--','; err:', er,'; h:', h,'; respH:', resp && resp.h);
  211. chkErrMax();
  212. },
  213. chkErrMax = function(){if(!errIMax) console.error('Too many err messages:', errNMax)}
  214. ,fileType ='PDF,DOC,docx,RTF,SWF,XLS,PPT,ODT,ODS,ODP,ODG'.split(',').map(function(x){return '&nbsp; '+x+'&nbsp; '})
  215. ,$l ={ru:{
  216. 'search in PDF files':'поиск по документам PDF'
  217. ,'search in':'искать по'
  218. ,'from / to':'за период'
  219. ,'past':['за последний','за последние','за последнюю']
  220. ,'day':'сутки'
  221. ,'days':['дня','дней']
  222. ,'week':'неделю'
  223. ,'weeks':['недели','недель']
  224. ,'month':'месяц'
  225. ,'months':['месяца','месяцев']
  226. ,'year':'год'
  227. ,'years':['года','лет']
  228. ,'hour':'час'
  229. ,'hours':['часа','часов']
  230. ,'Settings':'Настройки'
  231. ,'of userscript':'юзерскрипта'
  232. ,'reload page for effect':'перезагрузить страницу'
  233. ,'Interface language':'Язык интерфейса'
  234. ,'Less positions at the end of selects':'Меньше выбора в конце селектов'
  235. ,'Sites':'Сайты'
  236. },ua:{
  237. 'search in PDF files':'пошук по документах PDF'
  238. ,'search in':'шукати по'
  239. ,'from / to':'за період'
  240. ,'past':['за останній','за останні','за останню']
  241. ,'day':'добу'
  242. ,'days':['дні','днів']
  243. ,'week':'тиждень'
  244. ,'weeks':['тижня','тижнів']
  245. ,'month':'місяць'
  246. ,'months':['місяці','місяців']
  247. ,'year':'рiк'
  248. ,'years':['роки','рокiв']
  249. ,'hour':'годину'
  250. ,'hours':['години','годин']
  251. ,'Settings':'Настройки'
  252. ,'of userscript':'юзерскрипту'
  253. ,'reload page for effect':'перезавантажити сторінку'
  254. ,'Interface language':'Мова інтерфейсу'
  255. ,'Less positions at the end of selects':'Менше вибору в кінці селектів'
  256. ,'Sites':'Сайти'
  257. },by:{
  258. 'search in PDF files':'пошук па дакументах PDF'
  259. ,'search in':'шукаць па'
  260. ,'from / to':'за перыяд'
  261. ,'past':['за апошні','за апошнія','за апошнюю']
  262. ,'day':'суткі'
  263. ,'days':['дня','дзён']
  264. ,'week':'тыдзень'
  265. ,'weeks':['тыдня','тыдняў']
  266. ,'month':'месяц'
  267. ,'months':['месяца','месяцаў']
  268. ,'year':'год'
  269. ,'years':['года','гадоў']
  270. ,'hour':'гадзіну'
  271. ,'hours':['гадзіны','гадзін']
  272. ,'Settings':'Налады'
  273. ,'of userscript':'юзерскрипта'
  274. ,'reload page for effect':'перазагрузіць старонку'
  275. ,'Interface language':'Мова інтэрфейсу'
  276. ,'Less positions at the end of selects':'Менш выбару ў канцы селект'
  277. ,'Sites':'Сайты'
  278. },fr:{
  279. 'search in PDF files':'la recherche dans les fichiers PDF'
  280. ,'search in':'rechercher dans'
  281. ,'from / to':'pour la période'
  282. ,'past':['le dernier','dans les derniers','dans les derniers']
  283. ,'day':'jour'
  284. ,'days':['jours','jours']
  285. ,'week':'semaine'
  286. ,'weeks':['semaines','semaines']
  287. ,'month':'mois'
  288. ,'months':['mois','mois']
  289. ,'year':'an'
  290. ,'years':['ans','ans']
  291. ,'hour':'heure'
  292. ,'hours':['heures','heures']
  293. ,'Settings':'Paramètres'
  294. ,'of userscript':'de Userscript'
  295. ,'reload page for effect':'recharger la page pour effet'
  296. ,'Interface language':'Langue de l\'interface'
  297. ,'Less positions at the end of selects':'Moins de choix les longues listes'
  298. ,'Sites':'Les sites'
  299. },de:{
  300. 'search in PDF files':'Suche in PDF-Dateien'
  301. ,'search in':'Suche in'
  302. ,'from / to':'im Zeitraum'
  303. ,'past':['letzter','letztes','letzte']
  304. ,'day':'Tag'
  305. ,'days':['Tage','Tage']
  306. ,'week':'Woche'
  307. ,'weeks':['Wochen','Wochen']
  308. ,'month':'Monat'
  309. ,'months':['Monate','Monate']
  310. ,'year':'Jahr'
  311. ,'years':['Jahre','Jahre']
  312. ,'hour':'Stunde'
  313. ,'hours':['Stunden','Stunden']
  314. ,'Settings':'Einstellungen'
  315. ,'of userscript':'von Userscript'
  316. ,'reload page for effect':'Seite neu laden'
  317. ,'Interface language':'Sprache'
  318. ,'Less positions at the end of selects':'Weniger Auswahl in langen Listen'
  319. ,'Sites':'Websites'
  320. },es:{
  321. 'search in PDF files':'búsqueda en archivos PDF'
  322. ,'search in':'busca en'
  323. ,'from / to':'para el período'
  324. ,'past':['el último','en los últimos','en los últimos']
  325. ,'day':'día'
  326. ,'days':['días','días']
  327. ,'week':'Semana'
  328. ,'weeks':['semanas','semanas']
  329. ,'month':'mes'
  330. ,'months':['meses','meses']
  331. ,'year':'año'
  332. ,'years':['años','años']
  333. ,'hour':'hora'
  334. ,'hours':['horas','horas']
  335. ,'Settings':'Ajustes'
  336. ,'of userscript':'de userscript'
  337. ,'reload page for effect':'página para efecto de recargar'
  338. ,'Interface language':'Idioma de interfaz'
  339. ,'Less positions at the end of selects':'Menos elección en listas largas'
  340. ,'Sites':'Sitios'
  341. }}; //if !lang, then no hints
  342. addRules('.z-index-group_level_9{z-index: 11002}' //buttons above suggest
  343. +'.search2__button,.websearch-button{overflow:inherit}'
  344. +'.lsbb .xButt,.search2__button >.siteList, .search2__button .mini-suggest__button:not([role="button"]):not(.websearch-button){'
  345. +'z-index: 11002; width: 34px; height:17px; padding: 0 2px; line-height:14px; font-size:14px;'
  346. +'border:1px solid transparent; border-radius: 1px; background-color: rgba(214, 188, 76, 0.92); color:#fff; opacity:.6}'
  347. +'.search2__button >.siteList{width:31px; height:auto; padding: 1px 0 2px; text-align:center; font-weight: bold;'
  348. +'background-color: rgba(228, 189, 17, 0.7);} .search2__button >.siteList .lsb{font-weight: normal; color:#ece3dd}'
  349. +'.search2__button >.siteList .list.blockImp{display:block!important}'
  350. +'.search2__button >.siteList:after{display:block; border-left:3px solid rgba(228, 189, 17, 0.7); border-top:8px solid transparent;'
  351. +' border-bottom:9px solid transparent; content:""; position: absolute; left:32px; top:0; height:2px;}'
  352. +'.search2__button .mini-suggest__button:hover,.search2__button .xButt:hover{opacity:.85; color:#6f6e69;}'
  353. +'.search2__button .xButt:not(.sett):hover{background-color: rgba(226, 194, 27, 0.47);}'
  354. +'.search2__button .xButt .mini-suggest__button:hover{background-color: #e4d68c}'
  355. +'.siteList .xButt{display: block} .siteList .xButt .txt{padding: 0 2px 0 1px;} .siteList .sett .txt{background-color: #e2c043}'
  356. +'.siteList .settIn{display: none; width: 250px; padding: 2px 4px; text-align: left; border:1px solid #dacb97;'
  357. +'background-color: rgba(239, 235, 217, 0.94); color: #653} .siteList .settIn hr{margin:2px 0}'
  358. +'.sbibtd .sfsbc .nojsb, .siteList .sett:hover .settIn, .siteList .settIn.changed,'
  359. +'.siteList .settIn.changed .reload{display: block}.siteList .settIn .reload, .siteList.hiddn{display: none}'
  360. +'.select .button.button_checked_yes, .select .button.button_checked_yes .button__text{background-color: rgba(245, 226, 140, 0.7)}'
  361. +'.search2__button >.button_size_ws-head:first-child{width: 88px; line-height: 36px; height: 36px; padding:0; font-size: 16px; border:0; background:transparent}');
  362. var ff; (ff=function(CSPolicy){xLocStor({do:'get', key:'sett', val:setts, csp: CSPolicy, cB: function(prev,undef){
  363. S = prev || setts;
  364. S.dwmyh = S.dwmyh || setts.dwmyh; //temp. transitional expr.
  365. console.timeStamp = function(){};
  366.  
  367. CS({t:120, i:8, m: 1.6
  368. ,c: function(){
  369. return d && $q('.mini-suggest__button'); // $q('.suggest2-form__button');
  370. },
  371. o: function(dat){
  372. var lang = S.lang != null && S.lang || setts.lang
  373. ,sites = S.sites && (S.sites.length && S.sites[0] || S.sites.length >1) && S.sites
  374. || typeof sites =='string'&& [sites] || !S.sites && setts.sites || null;
  375. var strSites = sites && sites.join('\n').replace(/^\n/,'\n\n') ||''
  376. ,$L = $l[lang] || $l.ru; //default template of lang
  377. if(!lang || !$l[lang] || lang =='en') for(var l in $L){ //replace 'en' lang for default or substitution
  378. if($L[l] instanceof Array) for(var l2 in $L[l])
  379. $L[l][l2] = l;
  380. else
  381. $L[l] = l;
  382. }
  383. var $LSettings = $L['Settings'];
  384. if(sites && sites.length)
  385. sites.push($LSettings);
  386. var mainPg = /\/search\?/.test(lh)
  387. ,inputSearch = $q('.mini-suggest .mini-suggest__input') || $q('.input__control') //trueth place for 1 of 2 pages
  388. ,buttSearch = dat
  389. ,ua = lang=='ua', by = lang=='by',de = lang=='de'
  390. ,buttS ={
  391. site:{url:'site:'+ S.sites[0], txt:$L['search in']+' '+ S.sites[0], one:'day'} //you may comment this line
  392. ,'.. : ..':{url:'', txt:$L['from / to']}
  393. ,'1D':{url:'&tbs=qdr:d', txt:$L['past'][de?0:ua?2:1] +' '+ $L['day'], one:'day', up:13,lett:'D',itrv:1}
  394. ,'1W':{url:'&tbs=qdr:w', txt:$L['past'][ua||by?0:2] +' '+ $L['week'], one:'week', up:14,lett:'W',itrv:7}
  395. ,'1M':{url:'&tbs=qdr:m', txt:$L['past'][0] +' '+ $L['month'], one:'month', up:20,lett:'M',itrv:30.5}
  396. ,'1Y':{url:'&tbs=qdr:y', txt:$L['past'][de?1:0] +' '+ $L['year'], one:'year', up:10,lett:'Y',itrv:365.24}
  397. //,'1H':{url:'&tbs=qdr:h', txt:$L['past'][ua||de||by?2:0] +' '+ $L['hour'], one:'hour', up:23,lett:'H',itrv:1/24}
  398. //,DOC:{url:'&mime=doc', txt:$L['search in PDF files'].replace(/PDF/,'DOC'), up: fileType.length}
  399. ,PDF:{url:'&mime=pdf', txt:$L['search in PDF files'], up: fileType.length}
  400. }, ii = 0, iD = -1;
  401. !sites && delete buttS.site;
  402. buttSearch.parentNode.style.position ='relative';
  403. if(buttSearch && top == self) for(var i in buttS) if(i !='site'|| S.sites){ //buttons under search input line
  404. if(i.length ==2) iD++; else iD=-1;
  405. var bI = buttS[i], titl
  406. ,Gesch = ({m:'letzter',f:'letzte',n:'letztes'})['m,f,m,n,f'.split(',')[iD]]
  407. ,hint = function(j){return (j+1) +' '+ (j % 10 || j==10 ? $L[bI.one +'s'][j % 10 <4 && (j/10|0)!=1 ?0:1] : $L[bI.one]) }
  408. ,butt2 = $e({clone: i =='site'|| i.length ==2 || i=='PDF'
  409. ? $e({cl: 'siteList', cs: {cursor:'default'}, at: {site: S.sites[0], date: bI.url} })
  410. : i !='.. : ..'|| mainPg ? buttSearch : $e({cl: 'siteList hiddn'})
  411. ,clAdd:'xButt'
  412. ,atRemove: ['id', 'name','role']
  413. ,at: {value: iD !=-1 && S.dwmyh[iD] !=1 ? S.dwmyh[iD] + bI.lett : i
  414. ,innerHTML: '<span class=txt onclick=this.parentNode.click();return!1 title="' +(titl = lang || i=='site'|| i=='.. : ..'
  415. ? (iD==-1 || S.dwmyh[iD]==1 ? bI.txt : $L['past'][1] +' '+ hint(S.dwmyh[iD]-1)).replace(/letztes/,Gesch) :'')+'">'
  416. +(iD !=-1 && S.dwmyh[iD] !=1 ? S.dwmyh[iD] + bI.lett : i) +'</span>'
  417. ,title: titl}
  418. ,cs: {position: 'absolute', top: '33px', left: (-127 + 37 * (ii++ - (ii >2 && !mainPg))) +'px'}
  419. ,on: {click: (function(bI, i, iD){
  420. return /PDF|DOC|site/.test(i)
  421. ? function(ev){
  422. var doc, t = ev.target
  423. ,dat = (t.getAttribute('date')||t.parentNode.getAttribute('date')||'').replace(/^&\w+=/,'').toLowerCase();
  424. if(t.className =='defa')
  425. saveLocStor('','','remove'); $pd(ev);
  426. if(((t.getAttribute('site') ==null && t.parentNode.getAttribute('site') ==null)
  427. || t.getAttribute('site')==$LSettings || t.parentNode.getAttribute('site')==$LSettings)
  428. && !/PDF|DOC/.test(t.getAttribute('value'))) return;
  429. inputSearch.value = inputSearch.value.replace(/ site\:[\w.]*$/ig,'') +(/site/.test(i)
  430. ?' site:'+ (t.getAttribute('site') || t.parentNode.getAttribute('site')||''):'');
  431. //console.log('clic:',i,dat,bI,ev, t.className, inputSearch.value, ev.currentTarget, buttSearch.form)
  432. if(/PDF|DOC/.test(i)){ // check selection of types in the page (?)
  433. if(doc = $q('select[name="mime"]')){
  434. var opts = Array.prototype.slice.call(doc).reduce(function(memo, el, i){
  435. memo[el.value] = el; return memo;},{});
  436. var opt = opts[dat];
  437. if(opt)
  438. opt.selected = opt.selected ?'':'selected';
  439. }else
  440. $e({el: buttSearch.form, ap: $e({el: $q('input[name="mime"]')||'input'
  441. ,at:{type:'hidden', name:'mime', value: dat}}) });}
  442. //console.log('clic2:', /xButt|txt/.test(t.className) && i !='site', opt, opts)
  443. if(/xButt|txt/.test(t.className) && !(i=='site' && !(/list/.test(t.parentNode.className)
  444. || /list/.test(t.parentNode.parentNode.className)))) buttSearch.click();
  445. }: !bI.url ? function(ev){ //from-to date
  446. var el = $q('#cdrlnk'), o;
  447. el && el.dispatchEvent(((o = d.createEvent('Events')).initEvent('click', !0, !1), o));
  448. $pd(ev);
  449. }: function(ev){ //past interval
  450. var val = (ev.target.getAttribute('value')||ev.target.parentNode.getAttribute('value')).replace(/\D/g,'')
  451. ,dat = ev.target.getAttribute('date')||ev.target.parentNode.getAttribute('date')
  452. ,daysAgo = buttS['1'+ ((dat.match(/:(\w)/) ||[])[1] ||'d').toUpperCase()].itrv * val
  453. ,date = function(d){
  454. d = new Date(+new Date() - d * 86400000);
  455. return (d.getDate()>9?'':'0') + d.getDate() +'.'+ (d.getMonth()>8?'':'0')
  456. +(d.getMonth()+1) +'.'+ d.getFullYear();
  457. };
  458. //TODO select multi and save it to S and load to href
  459. location.href = '/search?text='+ encodeURIComponent(inputSearch.value)
  460. +('&from_date_full='+ date(daysAgo) +'&to_date_full='+ date(-1) || bI.url);
  461. //+(/[&?]tbm=/.test(lh) ? '&'+/tbm=[^&]*/.exec(lh)[0]:''); //TODO saving fileType of page
  462. S.dwmyh[iD] = +val;
  463. $pd(ev);
  464. ev.stopPropagation();
  465. saveLocStor();
  466. }
  467. })(bI, i, iD),
  468. mouseover: i =='site' || i.length ==2 || i=='PDF'? (function(bI,i){return function(ev){
  469. clearTimeout(bI.ww);
  470. $q('.list', ev.currentTarget).style.display ='block';
  471. $q('.list', ev.currentTarget).classList.add('blockImp');
  472. }})(bI,i) :'',
  473. mouseout: i =='site' || i.length ==2 || i=='PDF'? (function(bI,i){return function(ev){
  474. var t = ev.currentTarget;
  475. if(ev.relatedTarget && /^<option/i.test(ev.relatedTarget.innerHTML)){
  476. ($q('.settIn')||{classList: {add:function(){}}}).classList.add('changed'); return;}
  477. clearTimeout(bI.ww);
  478. bI.ww = setTimeout(function(){
  479. $q('.list',t).style.display ='none';
  480. $q('.list', t).classList.remove('blockImp');
  481. }, 570);
  482. }})(bI,i) :'',
  483. change: saveLocStor
  484. }
  485. ,apT: buttSearch.parentNode
  486. });
  487. bI.el = butt2;
  488. if(i =='site' || i.length ==2 || i =='PDF'){ //dropdown lists under some buttons
  489. var siteList = $e({cl:'list',cs:{display:'none'}, apT: butt2}), arr =[];
  490. for(var j =0; j <= bI.up -1 -(i=='1W'&& S.lastHoursLess ?4:0) -(i=='1M'&& S.lastHoursLess ?9:0); j++)
  491. if(i!='PDF' &&(i !='1H' || !S.lastHoursLess || j < 8 || j % 2 ))
  492. arr.push(hint(j));
  493. //console.log(S.sites,i, S.dwmyh);
  494. var list = i == 'site' ? sites||[] : i =='1D'&& !sites ? arr.concat([$LSettings])
  495. : i=='PDF' ? fileType : arr;
  496. for(var j in list) if(j !=0 || iD !=-1 && S.dwmyh[iD] !=1)
  497. var sI = list[j]
  498. ,butt3 = $e({clone: sI==$LSettings
  499. ? $e({cl: 'sett lsb'})
  500. : buttSearch
  501. ,clAdd:'xButt'
  502. ,atRemove:['id','name','role']
  503. ,at:{value: sI
  504. ,site: sI
  505. ,date: bI.url.replace(/doc$/, sI.replace(/&nbsp; /g,'').toLowerCase())
  506. ,title: sI==$LSettings || !lang ?'':(/site|PDF/.test(i) ? $L['search in'] +' '+ sI.replace(/&nbsp; /g,'')
  507. : j==0 ? bI.txt : $L['past'][1] +' '+ sI).replace(/letztes/,Gesch)
  508. ,innerHTML:'<span class=txt>'+ sI +'</span>'+ (sI != $LSettings &&!(!S.sites && i =='1H')
  509. ?'':'<div class="settIn">'
  510. +$LSettings +' '+ $L['of userscript'] +'<br/>"Yandex Extra Buttons"<hr/>'
  511. +$L['Interface language'] +': <select class="lang" style="width:70px">'
  512. +(function(){var s='<option'+ (lang=='en'?' selected':'') +'>en</option>';
  513. for(var i in $l)
  514. s+='<option'+ (lang==i ?' selected':'') +'>'+ i +'</option>';
  515. return s +'<option value="" '+ (lang==''?'selected':'') +'>en w/o hints</option>'})()
  516. +'</select><br>'
  517. +'<input type="checkbox" class="less" id="hoursLess" '+ (S.lastHoursLess ?'checked':'') +'/>'
  518. +'<label for="hoursLess" id="hoursLessL">'+ $L['Less positions at the end of selects'] +'</label><br>'
  519. +'<i><a href="#" class="defa" style="float: right">Default settings</a></i>'
  520. +$L.Sites +': <br><textarea class="sites" style="width:97%" rows=8>'
  521. + strSites +'</textarea><br>'
  522. +'<a class="reload" href=# onclick="location.reload();return!1">'
  523. + $L['reload page for effect'] +'</a>'
  524. +'</div>')}
  525. ,cs: {position: sI != $LSettings ?'static':'absolute',display:'block', width:'auto', height: sI != $LSettings ?'18px':'16px'
  526. ,margin:'2px 0 -1px -13px', padding:0, textAlign:'left', fontWeight:'normal', opacity:1}
  527. ,on:{click: function(ev){
  528. var less = $q('#hoursLess'), t = ev.target;
  529. if(less && /hoursLess/.test(t.id)){
  530. less.outerHTML = '<input type="checkbox" class="less" id="hoursLess"'
  531. +(less.getAttribute('checked')!=null ?'':' checked="checked"')+'/>';
  532. saveLocStor();}
  533. $pd(ev);
  534. }
  535. }
  536. ,apT: siteList
  537. });
  538. siteList.style.height ='auto'; siteList.style.textAlign ='center';
  539. }
  540. }
  541. }
  542. });
  543.  
  544. }, el: d.body});})(); setTimeout(function(){/*console.log('S1 ', cspState);*/if(cspState <3) ff('CSPolicyFrame');},2000);
  545. var saveLocStor = function(ev, val, do2){ var aaa,aab,aac, t = ev && ev.target.form || document.documentElement || document.body;
  546. xLocStor({do: do2 ||'set', key:'sett'
  547. , val:{lang: (aaa=d.querySelectorAll('.lang', t))[aaa.length-1].value
  548. ,sites: (aab=d.querySelectorAll('.sites', t))[aab.length-1].value.replace(/^[ \t]*|[ \n\t]*$/g,'')
  549. .split('\n')
  550. ,lastHoursLess: (aac=d.querySelectorAll('.less', t))[aac.length-1].checked
  551. ,dwmyh: S.dwmyh || setts.dwmyh
  552. }
  553. ,cB: function(prev){
  554. console.info('Settings are saved. prev=', prev);}
  555. });
  556. $q('.siteList .settIn').classList.add('changed');
  557. };
  558.  
  559. })({ //write "lang:''," to remove hints; 'en' for English hints (fr - Français, es - espagnol), 'ru' for Russian
  560. lang:''|| (navigator.languages && navigator.languages[1] || navigator.language.substr(0,2)) //='' if hide hints, or 2 letters from $l{}
  561. ,sites: [ //=array or one site in string
  562. '','slashdot.org','reddit.com','techcrunch.com','habrahabr.ru','geektimes.ru'
  563. ,'smashingmagazine.com','engadget.com'] //write your favorite sites
  564. ,lastHoursLess: 1 //=boolean - not show odd some values of hours after 8 h
  565. ,dwmyh: [1,1,1,1,1] //=array of numbers - current vals of days, weeks, months, years, hours
  566. });