I'm currently setting the window.location.pathname property to redirect the user to a relative URL. The new URL has parameters, so the line of JavaScript looks like this:
window.location.pathname = window.location.pathname.substring( 0, window.location.pathname.lastIndexOf( '/' ) + 1 ) + 'myPage.xhtml?u=' + selected_user.Username;
This is successful in Firefox, however Chrome encodes the question mark with '%3F' and the request subsequently fails.
I'm not sure if I'm using window.location properly. Do I need to use properties of window.location such as pathname or href? I've found that as soon as I set one property the location is reloaded, so for example, the search and pathname properties can't be set separately. Can window.location be set directly? I only need to set a relative URL with a parameter.
pathname
and many other properties oflocation
and links reflect only part of the URL:As you can see, the
?...
part of the URL is not part of thepathname
; it makes no sense to write a value containing?
tolocation.pathname
, as that part of a URL cannot contain a question mark. Chrome is correcting your mistake by encoding the character to a sequence that means a literal question mark, which doesn't terminatepathname
.These properties are great for breaking a URL into their constituent parts for you to process, but you probably don't want to write to them in this case. Instead, write to
location.href
. This represents the whole URL, but it's perfectly fine to write a relative URL to it; this will be worked out relative to the current value, so there is in fact no need to read and split thepathname
at all:Note the URL-encoding. If a username can contain characters other than alphanumerics you will probably need this to stop those characters breaking the parameter. Always URL-encode arbitrary strings before putting them into part of a URL.
Using
window.location.href
is considered the safest way to set a URL. I think this should fix the encoding problem.If that doesn't help, please show an example URL.
Try setting the
location.href
property instead ofwindow.location.pathname
.