-1

I am having a little bit of Greasmonkey trouble

I want to write a scrip that automatically adds a "?" to the end of every url fetched when using a forum (long story, but doing this prevents the caching issues the owners are having)

I have this, but it does what I want, however it keeps on redirecting and adding another "?" so i end up with "forum.domain.com/viewforum.php?f=4????????????" and it keeps adding another question mark without loading the forum

This is basic to me so i cannot work this out, so help would be appreciated.

// ==UserScript==
// @name       sort out caching issue
// @version    1.01
// @description  Adds parameter to sort caching issue
// @include      http://forum.domain.com/*
// @include      http://forum.domain.com/viewforum.php?f=4
// @include      http://forum.domain.com/viewforum.php?f=5
// @exclude      http://forum.domain.com/index.php
// @run-at document-start
// ==/UserScript==

window.location.replace (window.location.href + "~");

Im guessing there needs to be some sort of check to see if ts been run already, but as I am jumping on StackOverflow as a beginner, any help would be appreciated.

Thanks

Shaun
  • 3
  • 1

1 Answers1

0

Because you're adding a ~ to the end of the URL, it sounds like all you need to do is check to see if the final character in the current URL is a ~ or not. If not, then you can add it, and the page will refresh; else, do nothing, thus preventing the infinite refresh loop:

const { href } = window.location;
if (href.slice(-1) !== '~') {
  window.location.replace(href + '~');
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • perfect, thank you so much, this works nicely. It does take a fraction of a second longer to load but guessing this is down to the reload of the page or something? Sorry for the questions, i am still learning – Shaun Oct 27 '18 at 21:41
  • Yep, that sounds as expected - a `location.replace` will replace the page, which will take a bit longer than if nothing needs to be done with the original page. – CertainPerformance Oct 27 '18 at 21:42
  • ok, i'm back again as this didn't really solve the caching issue. Apparantly, to avoid the caching issues, i need to append a "&" followed by a random number to the end of the URL. so, with that in mind, how does one add "Math.random" to the end of the URL with the ampersand based on the code above? – Shaun Oct 28 '18 at 20:24
  • Use a regular expression to check if the URL ends in `&` followed by digits `if (!/&\d+$/.test(href)) window.location.replace(href + '&' + String(Math.random()).slice(2))` – CertainPerformance Oct 28 '18 at 20:37