How to change all links in a page?

可紊 提交于 2019-12-11 00:14:26

问题


For pages like this IP-direct, Google search:

http://62.0.54.118/search?&q=42&oq=42&sourceid=chrome&ie=UTF-8&filter=0


How can I change all the links in that page from search?q to search?&q=?

For example, I want to make the link:

http://62.0.54.118/search?q=42&ei=Xf5bUqHLOKeQ0AWV4YG4Cg&start=10&sa=N&filter=0

into:

http://62.0.54.118/search?&q=42&ei=Xf5bUqHLOKeQ0AWV4YG4Cg&start=10&sa=N&filter=0


How can I make Chrome change the links by automatic script or something like that?


回答1:


To change those links, on a static page (like your example):

  1. Search for applicable links.
  2. Loop through the links and change them. (Typically using regex.)

A complete userscript would like like this:

// ==UserScript==
// @name     _Modify select Google search links
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @include  http://62.0.54.118/*
// ==/UserScript==

var qLinks  = document.querySelectorAll ("a[href*='?q=']");

for (var J = qLinks.length - 1;  J >= 0;  --J) {
    var oldHref = qLinks[J].getAttribute ('href');
    var newHref = oldHref.replace (/\?q=/, "?&q=");

    //console.log (oldHref + "\n" + newHref);
    qLinks[J].setAttribute ('href', newHref);
}


Save the file as GoogleLinkModify.user.js and then drag it to the extensions page to install. (Or install the Tampermonkey extension and install the script via Tampermonkey).


Important:

  1. For AJAX-driven pages, install Tampermonkey and use waitForKeyElements().
  2. Google pages are a PITA to script. Beware that even though you change the href, many Google pages will ignore that and also sneakily redirect links just as you click on them. See or open other questions for more on that.



回答2:


Here is a regular expression that could work for you:

var url = 'http://62.0.54.118/search?q=42&oq=42&sourceid=chrome&ie=UTF-8&filter=0'
var regex = /(http:\/\/.*?search\?)(.*)/
console.log( url.replace(regex, '$1&$2') )

// 'http://62.0.54.118/search?&q=42&oq=42&sourceid=chrome&ie=UTF-8&filter=0'

You will need to loop through all the urls in the page and apply this to each of them.

Do you need help with modifying the HTML in the target page, or can you reach your solution from here?




回答3:


A succinct one-liner that can be bookmarked as a scriplet:

javascript:for(i in dl=document.links)dl[i].href=dl[i].href.replace(/(http:.*search[?])(q=.*)/,'$1&$2')

ie. a simple way to observe traversed SO links, whether related or linked or raw, irregardless:

javascript:for(i in dl=document.links)dl[i].href=dl[i].href.replace(/[?].q=1/,"")


来源:https://stackoverflow.com/questions/19362617/how-to-change-all-links-in-a-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!