Javascript:以编程方式向URL添加单词

时间:2014-09-04 06:13:19

标签: javascript search greasemonkey

我的问题

我厌倦了手动添加" dog"每次我使用谷歌。我不想要#34;狗"出现在我的搜索结果中。

例如:它应该是这样的

https://www.google.com/search?q=cat +-dog

https://www.google.com/search?q=baseball +-dog

代码:归功于krowe。

dog已替换为-torrent-watch-download

// ==UserScript==
// @name       Tamper with Google Results
// @namespace  http://superuser.com/users/145045/krowe
// @version    0.1
// @description  This just modifies google results to exclude certain things.
// @match      http://*.google.com
// @match      https://*.google.com
// @copyright  2014+, KRowe
// ==/UserScript==


function GM_main () {
    window.onload = function () {
      var targ = window.location;
      if(targ && targ.href && targ.href.match('https?:\/\/www.google.com/.+#q=.+') && targ.href.search("/+-torrent/+-watch/+-download")==-1) {
        targ.href = targ.href +"+-torrent+-watch+-download";
      }
    };
}

//-- This is a standard-ish utility function:
function addJS_Node(text, s_URL, funcToRun, runOnLoad) {
    var D=document, scriptNode = D.createElement('script');
    if(runOnLoad) scriptNode.addEventListener("load", runOnLoad, false);
    scriptNode.type = "text/javascript";
    if(text) scriptNode.textContent = text;
    if(s_URL) scriptNode.src = s_URL;
    if(funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()';
    var targ = D.getElementsByTagName('head')[0] || D.body || D.documentElement;
    targ.appendChild(scriptNode);
}

addJS_Node (null, null, GM_main);

问题是你必须在地址栏中输入搜索字符串才能使用。直接在Google搜索中输入的问题是onload事件不会触发。 我希望此脚本能够在Google搜索中使用

还有改进空间吗?

由于

1 个答案:

答案 0 :(得分:0)

由于Google正在开发哈希,您可以尝试:

window.addEventListener('hashchange', function(ev)
{
  if(! /[#&]q=(?:[^&]*\+)?-dog(?:\+|$)/i.test(location.hash))
    location.hash += '+-dog';
});

您可以使用new RegExp('the expression', modifiers)字符串动态准备RegExp。

考虑为google的查询版本实现替代方案,该版本在重负载(慢速脚本执行)时用作回退。

相关问题