21

I have something like http://domain.com/Pages/SearchResults.aspx?function=search&selectedserver=intranet&search_query=MyRecords and need to replace it by JavaScript with something similar to http://domain.com/Pages/SearchResults.aspx?function=loginsearch&user=admin&password=admin&selectedserver=intranet&search_query=MyRecords — so

function=search 

is being replaced with

function=loginsearch&user=admin&password=admin

inside the URL. Need help with what JavaScript should I save as a button on a browser's tool bar to click and have the URL in the address bar replaced.

user63503
  • 6,243
  • 14
  • 41
  • 44

6 Answers6

22
var url = window.location.toString();
window.location = url.replace(/function=search/, 'function=loginsearch&user=admin&password=admin');
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
11

The only way to update the displayed URL without reloading the page is history.pushState

window.history.pushState('', '', '/your-new-url');
tocqueville
  • 5,270
  • 2
  • 40
  • 54
4
 location.href = location.href.replace(
    'function=search&', 'function=loginsearch&user=admin&password=admin&')
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
1

My version. Works fine for me.

let url = window.location.toString();
window.history.pushState('', '', url.replace(searching_string, new_string));
Andriy Petrusha
  • 129
  • 1
  • 1
  • 8
0

You may find the dedicated library URI.js helpful, particularly setQuery() and addQuery() methods. I pasted this chunk of code directly into the console on that page and it seems to work:

var url = 'http://domain.com/Pages/SearchResults.aspx?function=search&selectedserver=intranet&search_query=MyRecords';
var uri = new URI(url);
var new_params = {'function': 'loginsearch', 'user': 'admin', 'password': 'admin'};
uri.setSearch(new_params);
console.log(uri.toString());

http://domain.com/Pages/SearchResults.aspx?function=loginsearch&selectedserver=intranet&search_query=MyRecords&user=admin&password=admin
<- undefined
>

It should be easy to turn this logic into a function (or a one-liner :)). As an aside, why are you passing the credentials right in the URL?

Leonid
  • 622
  • 3
  • 9
  • 22
0
var url             = window.location.href;               
window.location     = url.replace(/function=search/, 'function=loginsearch&user=admin&password=admin');
Black
  • 18,150
  • 39
  • 158
  • 271