简体   繁体   中英

Greasemonkey script to remove parameters from URL

I have this URL:

http://website.com/wp-content/uploads/2014/11/this-is-an-image_0120(pp_w820_h548).jpg

I want delete a parameter from the URL to look like this:

http://website.com/wp-content/uploads/2014/11/this-is-an-image_0120.jpg

How is it possible with Greasemonkey?

var links = document.getElementsByTagName("a");
for(var i = 0, l = links.length; i < l; i++) {
    var elements = links[i];
    elements.innerHTML = document.body.innerHTML.replace(/(pp_w820_h548)/gi, '');
}

I want also the width and height numbers will be unknown variables. Sometimes the images are png, so deleting everything after the (, and adding ".jpg" again to the end not the best solution.

SORRY! I meant for targeting img element, not the a. So this is an image, not a link.

Also pp need to be in there, because I only want to remove on the prophoto WP blogs.

So, this is it:

var links = document.getElementsByTagName("img");
for(var i = 0, l = links.length; i < l; i++) {
    var images = links[i];
    images.src= images.src.replace(/\(pp_w\d+_h\d+\)/gi, '');
}

UPDATE

The script only works with images which is near to viewport. Lazyloaded elements on the page still using the plus strings in url.

Is it possible with Greasemonkey to phisically change the HTML, not just in DOM?

var links = document.getElementsByTagName("a");
for(var i = 0, l = links.length; i < l; i++) {
    var a = links[i];
    a.href= a.href.replace(/\(pp_w\d+_h\d+\)/gi, '');
}

Example: http://jsfiddle.net/houp0qv0/

If you really don't know what's going to be inside the parentheses (for example, if the pp_ prefix may change), you can use:

var links = document.getElementsByTagName("img");
for(var i = 0, l = links.length; i < l; i++) {
    var link = links[i];
    link.src = link.src.replace(/\(.+\)/gi, '');
}

Or even:

link.src = link.src.replace(/\([a-zA-Z\d]+_[a-zA-Z\d]+_[a-zA-Z\d]+\)/gi, '');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM