Question

I'm trying to have a simple bookmarklet which adds a short parameter at end of any URL

I use ?clearcache to empty an internal cache, so in order not to type it each time, I'm looking for a simple solution

My site is

http://subdomain.mysite.net/ 

and with the bookmarklet I want to make the URL go to

http://subdomain.mysite.net/?clearcache

Same with deeper pages, as I would like it to go to

http://subdomain.mysite.net/some-page/?clearcache

I'm currently trying with

javascript:location=location.href.replace(/http:/g,"/?clearcache")

but it isn't working

When I click on that bookmarklet, my URL becomes

http://subdomain.mysite.net/?clearcache//subdomain.mysite.net/

I feel I am close to it, but I just need a small tip from experts. I hope for a a reply. Thanks

Was it helpful?

Solution

This should solve your problem:

Code

javascript:void((function(){var loc = location.href; loc.indexOf("?") == -1 ? (location.href = loc+"?clearcache") : (location.href = loc+"&clearcache");})());

Explanation

Check if any other query string parameters exists. If yes, then appends clearcache at the end using an & or append to the URL using ?.

OTHER TIPS

Here is a useful answer for those wondering how to do this for 'mod_pagespeed', totally inspired by the above answers.

javascript:void((function(){var loc = location.href; if (loc.indexOf('PageSpeed') >= 0) return; loc.indexOf("?") < 0 ? (location.href = loc+"?PageSpeed=off") : (location.href = loc+"&PageSpeed=off");})());

Building on Vikram Deshmukh's answer here is a version that uses a varying cache-busting parameter and replaces it every time it is used.

Expanded version:

javascript:void((function () {
    'use strict';
    let href;
    if (document.location.search === '') {
        href = document.location.href + '?_=' + Date.now();
    } else {
        let params = new URLSearchParams(document.location.search.substring(1));
        if (params.get('_') === null) {
            href = document.location.href + '&_=' + Date.now();
        } else {
            params.set('_', Date.now());
            href= document.location.href.substring(0, document.location.href.indexOf('?') + 1) + params.toString();
        }
    }
    document.location.assign(href);
})());

Compact version:

javascript:void((function () { let href; if (document.location.search === '') { href = document.location.href + '?_=' + Date.now(); } else { let params = new URLSearchParams(document.location.search.substring(1)); if (params.get('_') === null) { href = document.location.href + '&_=' + Date.now(); } else { params.set('_', Date.now()); href= document.location.href.substring(0, document.location.href.indexOf('?') + 1) + params.toString(); } } document.location.assign(href); })());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top