Best way to modify URL parameters with js - javascript

I trying to modify URL parameters, but I can't find a perfect way.
First I tried with:
window.location.href = window.location.href + '?test';
The problem is, that the page reloads and it is just added to the url.
Then I tried with:
window.location.href = String( window.location.href ).replace( "?test", "" );
This works perfect, the part I want to replace, gets replaced/deleted, but the page reloads every time...
Then I read about:
window.history.pushState( {} , 'test', '?test' );
But this doesn't work somehow...
My aim is to add and replace/delete URL strings, when buttons were clicked to control functions.
E.g.
The URL is http://www.example.com/?showoverlay&?showhint
So for example this shows an overlay and a hint tooltip based on these URL parameters.
When the user closed the overlay, the part "showoverlay" should be removed without a page reload. So the URL is:
http://www.example.com/?showhint

Have you tried using replaceState? It replaces the history without reloading the page and might fit your use case.
window.history.replaceState(data, title [, url ] );
https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_replaceState()_method
If you need to keep other parts of the url, make sure to store it in a separate variable and attach it back in the url.
This is roughly how you can get each part of your URL:
let url = window.location.origin + window.location.pathname + window.location.search
And then you just add it back with
window.history.replaceState({}, '', url + '&yourNewParameters=value')

Related

How to clear additional info from the redirect link?

I'm making discord login oauth2 in javascript, and I've set that when it's done it redirects me on '/auth', but when I'm on that page url has some other information in url, it's like '/auth#token_type=Bearer&access_token=12ekasd&expires_in=123123&scope=identify'.. Is it possible to change that url so it says just '/auth'? I've tried with window.location.href = '/auth' but nothing is being changed.
window.onload = () => {
what to code here?
}
The history API allows you to update the URL shown without actually redirecting the page.
window.history.replaceState({}, '', window.location.pathname);
This code should redirect you to the current path but without any hash or query string.
If you need to use the hash or query string in your code, make sure to save them before running this, since it also removes them from window.location.

JS: Reload the page without a specific param

I want to reload the page in Javascript without a specific param ie.
Let's say I want to reload www.domain.com/abc?num=4&something=1
But I want to reload www.domain.com/abc?number=4 only
Unfortunately the following keeps all of the params which isn't fit for my use case:
document.location.reload(false)
and:
window.location.href = window.location.pathname;
gets rid of every parameter and just navigates to the path. Is there a way to delete a query param from window.location before navigating back to it?
location.href=location.href.replace(/&?somthing=([^&]$|[^&]*)/i, "");

Passing Url params from one page to another

So I have a filter form on a page that show paginated results. Currently when you apply the filter settings using a get request everything works but when you try to switch pages it resets. I have thought of passing a url from one page to another using a script like the one below. This copies the url but does not actually change the page, just copies the string. You can see in the urls below that the url does change page but the actual webpage stay on the first page regardless of the url. I am using Django and Django filters. Maybe a there is a better jQuery solution, Any suggestions?
script
document.querySelectorAll('.fqs')
.forEach((el) => el.attributes.href.value += window.location.search);
Url
Without script:
/relations/?createdBy=&occursIn=&createdAfter=&createdBefore=&terminal_nodes=&project=1
With Script:
/relations/?page=2?createdBy=&occursIn=&createdAfter=&createdBefore=&terminal_nodes=&project=1
Next Page Link
<a class="fqs" href="?page={{ relations.next_page_number }}">Next ยป</a>
Url when pressing previous button
?page=1&page=2&createdBy=&occursIn=&createdAfter=&createdBefore=&terminal_nodes=&project=1
If I understand correctly you're adding pagination server-side ?page={{...}} and you adding already existing url parameters via js.
The resulting urls have two ? in it which may be why the link doesn't give you the correct page.
location.search includes the ? so to add that to your ?page=x you'd have to replace ? with &:
document.querySelectorAll('.fqs')
.forEach((el) => el.attributes.href.value += window.location.search.replace("?", "&"));
EDIT: if this works it may stop working on next pages as location.search would then include page=x giving duplicate page query parameters.
To filter out page parameter from location.search you could do something like:
document.querySelectorAll('.fqs')
.forEach((el) => {
var params = window.location.search.replace("?", "&").split("&");
params = params.filter((v) => v.indexOf("page") == -1).join("&");
el.attributes.href.value += params;
});
BTW, note that arrow functions don't work in legacy browsers like IE11.
In order to accomplish this I decide to not use any javascript at all and use python instead. I added
gt = request.GET.copy()
if 'page' in gt:
del gt['page']
context = {
'paginator': paginator,
'relations': relations,
'params': urlencode(gt),
'filter': filtered,
}
to my view. It copies the params, then deletes the param matching page and encodes in the context.

How to Perform Javascript redirect url with by Preserving URL parameter

How to Perform Javascript redirect url with by Preserving URL parameter of orignal URL?
eg
original url: http://test.com?a=1&b=2
Redirect to: http://sample.com?a=1&b=2
The following will get the current URL querystring:
var query = window.location.search;
That can then be used in the redirect:
window.location.replace('sample.com' + query);
DOCS
Update
The .replace() method will remove the current URL from the browser history. If you want to retain the current URL use .assign() as mentioned by #igor
Modify the location object:
location.href = location.href.replace ( new RegExp("^" + "http://test.com"), "http://sample.com/" );
The statement replaces the start of the url from which the current document has been loaded. The resource from the new url will be loaded automatically.
Your sample urls do not contain path and fragment portions ( like in http://test.com/the/path/compon.ent?a=1&b=2#a_fragment). They are accessible as
location.pathname // 'http://test.com/the/path/compon.ent'
location.hash // '#a_fragment'
Note that the occurrence of these url components suggest to expressly compose the new url the way #MattSizzle outlines in his answer.

How to remove params from URL after form is submitted?

When I use the following link in my browser, a record is populated in the form on this page to edit.
http://vcred.dev/#personal/myacademicdetail?record_id=15
When I click 'SAVE' button, record is successfully updated in database and form with updated values is still in front of me. It is OK for me. But I have only one problem after form is posted. In Address bar URL is still same as before post.
http://vcred.dev/#personal/myacademicdetail?record_id=15
But I want short URL without params in address bar after my form is posted like this:
http://vcred.dev/#personal/myacademicdetail
How it is possible using javascript?
Since you are using a hash in the URL, you could do the following in JavaScript:
location.href = location.protocol + "//" +
location.host +
location.pathname +
location.hash.split('?')[0];
This will not cause a page refresh, as described in this Stack Overflow post: How do I, with javascript, change the URL in the browser without loading the new page?
As far as Zend Framework goes, after you save the record use:
$this->_redirect('#personal/myacademicdetail');
This will tell the user's browser to go to the URL.
I'd do it like this, using PHP:
$referer_host = $_SERVER[ "HTTP_HOST" ];
$referer_uri = explode( "?", $_SERVER[ "REQUEST_URI" ] );
$referer = $referer_host . $referer_uri[ 0 ];
I assumed you might want to see also PHP solution as you've mentioned zend-framework as one of your tags.
I'd simply explode URL like this and then use headers for redirect.

Categories

Resources