2

I am looking for a userscript that replaces the part of URL if certain values are found in it. Below code seems to be working and replacing the URL, but problem is that it keeps on reloading/refreshing the page after URL is changed. I am new to all this, what am I doing wrong?

// @include      http://*
// @include      https://*
// @run-at       document-start
// ==/UserScript==

var url = window.location.href;

if (url.search("images.abc.com") >= 0) {
    url = url.replace('300','620');
    window.location = url;
}
SarmadK
  • 123
  • 1
  • 2
  • 14

1 Answers1

4

Your're using a window.location=url which changes the windows location and your page refreshes. You could do something like this to update the url without reloading the page.

Changing only what's after hash - old browsers

document.location.hash = 'lookAtMeNow';  

Changing full URL. Chrome, Firefox, IE10+

history.pushState('data to be passed', 'Title of the page', '/test');  

The above will add a new entry to the history so you can press Back button to go to the previous state. To change the URL in place without adding a new entry to history use

history.replaceState('data to be passed', 'Title of the page', '/test');

Full Solution

var url = window.location.href;

if (url.search("images.abc.com") >= 0) {
    url = url.replace('300','620');
    /*window.location = url;*/
    history.pushState('data if any', 'Title of the page if any', url);
    history.replaceState('data if any', 'Title of the page if any', url);
}
root
  • 518
  • 4
  • 20