Search code examples
javascriptpngjpegtampermonkeywebp

Tampermonkey method to drop the ".webp" extension for all ".jpg.webp" and ".png.webp" images on a page?


I have to download and re-upload a lot of images for work. Generally, the images I download from the webpage/server will come in the format of "XXX.jpg.webp" and "XXX.png.webp." Unfortunately, upon re-uploading them elsewhere, the system I use will not accept the ".webp" file extension. After I download the images with the ".webp" filetype, I'll have to convert them into pure ".jpg" and ".png" sans ".webp" to use them for my purposes.

As it stands, I have written a Tampermonkey script (in Javascript) in an attempt to remedy this problem, but it only works if I open a given ".webp" image in a separate tab and then right-click and save. This method strips the image of the ".webp" upon saving, but if and only if I open it in a separate tab and right-click to save. Instead, I would like to strip the images of the ".webp" extension and convert them into their ".png" or ".jpg" format on the very page that I find them, without having to open the image in a separate tab at all. Here's the current script I'm working with - again, it only works when I open the image in a separate tab:

document.querySelectorAll('img[src$=".jpg.webp"]').forEach(item =>
    item.src = item.src.replace('.webp', ''));

document.querySelectorAll('img[src$=".png.webp"]').forEach(item =>
    item.src = item.src.replace('.webp', ''));

And here is an example of a webpage that I do this for: https://www.shareably.net/mom-helps-single-dad-groceries/. Notice how the images have a ".webp" extension.

How can I go about altering the above script or getting a solution that converts these images on the original webpage and not in a separate tab? It would ultimately save me a ton of time. Any and all guidance would be much appreciated. Cheers!


Solution

  • An awesome user on reddit.com/r/AskProgramming helped me out with the solution. Seems like I was close. Here's the new working script:

    document.querySelectorAll('img[src$=".webp"]').forEach(item => {
      item.src = item.src.replace('.webp', '');
      item.srcset = '';
    });
    

    Discussion of the solution can be found here: https://old.reddit.com/r/AskProgramming/comments/lslvvb/tampermonkey_method_to_drop_the_webp_extension/